Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get layout height and width at run time android

Tags:

How can I get width and height of a linear layout which is defined in xml as fill_parent both in height and width? I have tried onmeasure method but I dont know why it is not giving exact value. I need these values in an Activity before oncreate method finishes.

like image 950
MGDroid Avatar asked Aug 22 '12 08:08

MGDroid


2 Answers

Suppose I have to get a LinearLayout width defined in XML. I have to get reference of it by XML. Define LinearLayout l as instance.

 l = (LinearLayout)findviewbyid(R.id.l1);
ViewTreeObserver observer = l.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                // TODO Auto-generated method stub
                init();
            l.getViewTreeObserver().removeGlobalOnLayoutListener(
                    this);
        }
    });

protected void init() {
        int a= l.getHeight();
            int b = l.getWidth();
Toast.makeText(getActivity,""+a+" "+b,3000).show();
    } 
    callfragment();
}  
like image 55
MGDroid Avatar answered Sep 21 '22 16:09

MGDroid


The width and height values are set after the layout has been created, when elements have been placed they then get measured. On the first call to onSizeChanged the parms will be 0 so if you use that check for it.

Little more detail here https://groups.google.com/forum/?fromgroups=#!topic/android-developers/nNEp6xBnPiw

and here http://developer.android.com/reference/android/view/View.html#Layout

Here is how to use onLayout:

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int width = someView.getWidth();
    int height = someView.getHeight();
}
like image 32
tom502 Avatar answered Sep 20 '22 16:09

tom502