的getWidth()和getHeight()总是返回0。自定义视图 [英] getWidth() and getHeight() always returning 0. Custom view

查看:387
本文介绍了的getWidth()和getHeight()总是返回0。自定义视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个片段,我用充气多个子视图的布局。我需要获得其中之一是一个自定义视图的尺寸(宽度和高度)。

In a Fragment, I am inflating a Layout with multiple child View. I need to get the dimensions (width and height) of one of them which is a custom view.

在自定义视图类的,我可以很容易地做到这一点。但是,如果我尝试从片段做到这一点,我总是得到0的尺寸。

Inside the custom view class I can do it easily. But if I try to do it from the fragment I always get 0 as dimensions.

 public void onViewCreated(View view, Bundle savedInstanceState) {

    super.onViewCreated(view, savedInstanceState);
    View culoide = view.findViewWithTag(DRAW_AREA_TAG);
    Log.d("event", "culoide is: "+culoide.getWidth()); // always 0
}

我想,onViewCreated应该是正确的地方得到它,但也出现这种情况。我试过super.onViewCreated之前,在调试它看起来像'findViewWithTag找到正确的观点,试图与API 7 V4只支持。

I figure that onViewCreated should be the right place to get it, but well this happens. I tried before super.onViewCreated, in debug it looks like 'findViewWithTag' finds the right view, tried with api 7 v4 support only.

任何帮助吗?

推荐答案

您必须等待,直到第一个测量和布局,以获取非零值的getWidth()后的getHeight()。你可以做到这一点<一个href="http://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html"><$c$c>ViewTreeObserver.OnGlobalLayouListener

You must wait until after the first measure and layout in order to get nonzero values for getWidth() and getHeight(). You can do this with a ViewTreeObserver.OnGlobalLayouListener

public void onViewCreated(View view, Bundle saved) {
    super.onViewCreated(view, saved);
    final ViewTreeObserver observer = view.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                observer.removeOnGlobalLayoutListener(this);
            } else {
                observer.removeGlobalOnLayoutListener(this);
            }

            // get width and height of the view
        }
    });
}

这篇关于的getWidth()和getHeight()总是返回0。自定义视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆