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.
Jens Vossnack's approach works fine. However, I found that the onGlobalLayout() method of GlobalLayoutListener is called repeatedly, which may not be appropriate in certain cases.
I got a simpler approach working.
First of all, you should use
match_parent
instead offill_parent
(deprecated).When you do
int width=layParamsGet.width;
, you take the right result which is-1
corresponding atfill_parent
. If you wan't to get the real width, you need to waitonMesure()
call and useIf you look at the value for
FILL_PARENT
(you should be usingMATCH_PARENT
sinceFILL_PARENT
is now deprecated) you will notice the value for it is -1.LayoutParams
are simply attributes for how your view should look. Once the view is inflated and looks the way the params specify, the view does not go back and change those Params to reflect the actual values of the view (width/height/etc).If you wanted to get the actual width of your view you would have to call
getWidth()
on your view once the layout has been inflated and displayed. CallinggetWidth()
before your layout has been displayed will result in 0.You can try to listen to the globalLayout event, and get the width in there. You probably get the -1 because you are trying to get the width before the views are layed-out.
(vto is the view you want to get the width of)
layoutGet.getWidth()
should work out