[英]Android - getting the width of a button which is set to wrap_content
I am trying to get the width of a button whose android:layout_width
is set to wrap_content
. 我试图获得一个按钮的宽度,其android:layout_width
设置为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. 当我尝试使用getMeasuredWidth()
在onCreate()
执行此操作时,我得到零值,因为我认为视图还没有准备好。
When should I get the width then? 我什么时候应该得到宽度呢? Is there any listener I can hook to when view is done initializing? 在查看初始化时,是否有任何可以挂钩的监听器?
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. 在完成子视图的布局之前调用onCreate。 So the width and height is not calculated yet. 所以宽度和高度尚未计算。 To get the height and width. 获得高度和宽度。 Put this on the onCreate method 把它放在onCreate方法上
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();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.