[英]In Android how to get the width of the Textview which is set to Wrap_Content
[英]Android - getting the width of a button which is set to wrap_content
我試圖獲得一個按鈕的寬度,其android:layout_width
設置為wrap_content
。 當我嘗試使用getMeasuredWidth()
在onCreate()
執行此操作時,我得到零值,因為我認為視圖還沒有准備好。
我什么時候應該得到寬度呢? 在查看初始化時,是否有任何可以掛鈎的監聽器?
您可以將樹觀察器添加到布局中。 這應該返回正確的寬度和高度。 在完成子視圖的布局之前調用onCreate。 所以寬度和高度尚未計算。 獲得高度和寬度。 把它放在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.