Hiren Patel Hiren Patel - 5 months ago 36
Android Question

How to get programatically / runtime width and height of Relative / Linear layout in android?

I required runtime dimensions of Relative/Linear Layout.

activity_home.xml:

<RelativeLayout
android:id="@+id/rlParent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</RelativeLayout>


HomeActivity.java:

private int width, height;

RelativeLayout rlParent = (RelativeLayout) findViewById(R.id.rlParent);

w = rlParent.getWidth();
h = rlParent.getHeight();

Log.i("Width-Height", width+"-"+height);


Please share your thoughts.

Answer

Well I have implemented by this way:

LinearLayout linearLayout = (LinearLayout)findViewById(R.id.layout);
ViewTreeObserver viewTreeObserver = linearLayout.getViewTreeObserver(); 
viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
        linearLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        int width  = linearLayout.getMeasuredWidth();
        int height = linearLayout.getMeasuredHeight(); 

    } 
});

This example is for Linear layout, for Relative layout follow same process.

Hope this would help you.