How to get height in pixels of LinearLayout with layout_weight

Usman picture Usman · Apr 28, 2014 · Viewed 8.6k times · Source

this is my first post. I am learning to code in java for android apps. I am using a LinearLayout "variable named: ll" with a predefined layout_weight (which I want to change whenever I want in the future) and height and width set to MATCH_PARENT. I want to get the height of this LinearLayout in pixels. I fill this using java (ll.addView(variableForAnObject);). I am trying to get its height using ll.getLayoutParams().height; but I am getting -1. Because I believe this is the constant for MATCH_PARENT. Setting the height to 0dp makes the ll invisible and gives height as 0.

Please tell me if there's a way to get its height. I think I can do this by getting screen height using DisplayMetrics and making nearly impossible calculations (for me, at least) but this will be too complex.

Answer

xgc1986 picture xgc1986 · Apr 28, 2014

try with ll.getHeight() should work

if not, it's because android has not yet calculed its bounds, then:

//inside of onCreate method should work
ll.post(new Runnable() {
    @Override
    public void run() {
        //maybe also works height = ll.getLayoutParams().height;

        height  = ll.getHeight();

    }
});