我想获得的一个按钮的宽度的android:layout_width
设置为 WRAP_CONTENT
。当我尝试这样做,在的onCreate()
使用 getMeasuredWidth()
,我得到的值为零,因为我觉得认为还没有准备好。
I am trying to get the width of a button whose android:layout_width
is set to wrap_content
. When I try to do that in onCreate()
using getMeasuredWidth()
, I get a value of zero because I think the view is not ready yet.
我什么时候应该得到的宽度呢?有没有听众,我可以钩到时查看完成初始化?
When should I get the width then? Is there any listener I can hook to when view is done initializing?
您可以添加一棵树观测到布局。这将返回正确的宽度和高度。的onCreate被称为子视图的布局完成之前。这样的宽度和高度,不计算尚未。要获得的高度和宽度。将这个在onCreate方法
You can add a tree observer to the layout. This should return the correct width and height. onCreate is called before the layout of the child views are done. So the width and height is not calculated yet. To get the height and width. Put this on the onCreate method
LinearLayout layout = (LinearLayout)findViewById(R.id.YOUD VIEW ID);
ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = layout.getMeasuredWidth();
int height = layout.getMeasuredHeight();
}
});