0

How can I get the width of an ImageButton that is set in XML to 0 and has size from the weight?

<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>

How do I get this value that was automatically set by the weight?

As set in XML as 0, if I do: imageButton.getWidth(); or imageButton.getLayoutParams().width(); both return 0 as in XML.

Woton Sampaio
  • 469
  • 6
  • 24

4 Answers4

1

It is possible using below snippet:

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(); 
    } 
});
aminography
  • 21,986
  • 13
  • 70
  • 74
1

You should use 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;
    }
});
Anubhav Gupta
  • 2,492
  • 14
  • 27
0
Button button;
button = (Button) findViewById(R.id.button);

int buttonWidth = button.getWidth();

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

// Layout Image enter image description here

// Result

enter image description here

0

It's giving 0 because you have to make sure that the integer in which you store width is not declared as final.

It should be not like this: Click to see Image