Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: get width of Layout programatically having fill_parent in its xml

I have the a LinearLayout with width set in xml as fill_parent , now i need its width at runtime programatically. So i did this:

    LinearLayout layoutGet=(LinearLayout) findViewById(R.id.GameField1);
    LayoutParams layParamsGet= layoutGet.getLayoutParams();
    int width=layParamsGet.width;

But width value on debugging was found to be -1, anybody with idea why can't i get the exact width at runtime for LinearLayout with fill_parent set in layout xml.

like image 981
Najeebullah Shah Avatar asked Aug 06 '13 13:08

Najeebullah Shah


1 Answers

I got a simple approach working.

myLayout = (RelativeLayout) findViewById(R.id.my_layout);
myLayout.post(new Runnable() 
    {

        @Override
        public void run()
        {
            Log.i("TEST", "Layout width : "+ myLayout.getWidth());

        }
    });

Jens Vossnack's approach mentioned below works fine. However, I found that the onGlobalLayout() method of GlobalLayoutListener is called repeatedly, which may not be appropriate in certain cases.

like image 108
Tony Avatar answered Oct 05 '22 11:10

Tony