的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()
。你可以做到这一点ViewTreeObserver.OnGlobalLayouListener$c$c>
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
}
});
}