Rohit Rohit - 5 months ago 18
Android Question

Get height and width of a layout programatically

I have designed an layout in which

LinearLayout
has 2 children
LinearLayout
and
FrameLayout
and in each child I put different views.

I just wanted to measure height and width of
FrameLayout
so that I could serve my purpose.

In program I am using

int height,width;

FrameLayout fr=(FrameLayout)findviewbyid(R.id.fr);
height=fr.getHeight();
width=fr.getWidth();


returns value as
0
for both

Even I tried with following code
int height,width;

FrameLayout fr=(FrameLayout)findviewbyid(R.id.fr);
height=fr.getMeasuredHeight();
width=fr.getMeasuredWidth();


returns same value
0


and finally I tried with following code,
int height,width;

FrameLayout fr=(FrameLayout)findviewbyid(R.id.fr);
height=fr.getgetLayoutParams().height();
width=fr.getLayoutParams().width;


returns me
-2
and
-1


I want the solution to get height and width of any layout programatically??

Answer

The view itself, has it's own life cycle which is basically as follows:

-Attached

-Measured

-Layout

-Draw

So, depending on when are you trying to get the width/height you might not see what you expect to see, for example, if you are doing it during onCreate, the view might not even been measured by that time, on the other hand if you do so during onClick method of a button, chances are that by far that view has been attached, measured, layout and drawn, so, you will see the expected value, you should implement a ViewTreeObserver to make sure you are getting the values at the proper moment.

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

    } 
});

Hope it Helps.

Regards!