DaveNOTDavid
DaveNOTDavid

Reputation: 1803

Getting the size of an inner layout in pixels

With the following Java and XML code, I was wondering how to retrieve the dimensions in pixels of an inner/child layout (LinearLayout, whereas the parent is RelativeLayout with paddings of 20dp) properly:

Java code:

public class TestActivity extends Activity {
    private LinearLayout linLay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        linLay = (LinearLayout)findViewById(R.id.linLay);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT);
        linLay.setLayoutParams(lp);

        getDimensions();
    }

    private void getDimensions() {
        System.out.println(linLay.getHeight());
        System.out.println(linLay.getWidth());
    }
}

XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp" >

    <LinearLayout
        android:id="@+id/linLay"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true">

    </LinearLayout>
</RelativeLayout>

... Since I get outputs of 0 for the dimensions, I am aware that the LinearLayout needs to be set first on the screen before I could retrieve the dimensions... But what am I doing wrong here?

Upvotes: 0

Views: 167

Answers (1)

tiny sunlight
tiny sunlight

Reputation: 6251

It didn't get its dimensions at the time you try to output them.You can just add a delay or just use method below.

private void getDimensions() {

    ViewTreeObserver vto = linLay.getViewTreeObserver();  
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
        @Override 
        public voidonGlobalLayout() { 
            linLay.getViewTreeObserver().removeGlobalOnLayoutListener(this);      
            int height =linLay.getMeasuredHeight(); 
            int width =linLay.getMeasuredWidth();  
            System.out.println(height);
            System.out.println(width);
        }  
    });

}

Upvotes: 1

Related Questions