簡體   English   中英

如何獲得ImageButton寬度

[英]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;
    }
});
Button button;
button = (Button) findViewById(R.id.button);

int buttonWidth = button.getWidth();

// Showing the Result
Toast.makeText(MainActivity.this, ""+buttonWidth, Toast.LENGTH_SHORT).show();

//布局圖片 在此處輸入圖片說明

//結果

在此處輸入圖片說明

它的值為0,因為您必須確保存儲寬度的整數未聲明為final。

它應該不是這樣的: 單擊以查看圖像

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM