[英]How to get ImageButton width
如何獲取以XML設置為0並具有權重大小的ImageButton的寬度?
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:orientation="horizontal">
<ImageButton
android:id="@+id/fluido"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:tint="@color/icon"
android:layout_weight="0.33"
app:srcCompat="@drawable/fluido" />
<......../>
</LinearLayout>
如何獲得該重量自動設置的值?
正如我在XML中設置為0一樣: imageButton.getWidth();
或imageButton.getLayoutParams().width();
都以XML形式返回0。
可以使用以下代碼段:
yourView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
// Correct view dimensions are here:
int width = yourView.getMeasuredWidth();
int height = yourView.getMeasuredHeight();
}
});
您應該使用addOnPreDrawListener
view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
{
@Override
public boolean onPreDraw()
{
if (view.getViewTreeObserver().isAlive())
view.getViewTreeObserver().removeOnPreDrawListener(this);
// put your code here
return false;
}
});
它的值為0,因為您必須確保存儲寬度的整數未聲明為final。
它應該不是這樣的: 單擊以查看圖像
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.