Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get height in pixels of LinearLayout with layout_weight

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.

like image 771
Usman Avatar asked Apr 28 '14 12:04

Usman


2 Answers

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();

    }
});
like image 66
xgc1986 Avatar answered Oct 18 '22 04:10

xgc1986


It is -1 because its dimensions have not yet been set, whenever you set layout it takes some time to compute the actual values including height, width etc.

Use OnLayoutListener to listen when it has finished with the layout.

layout.onLayoutChange (View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
    //Extract values here
    height = view.getHeight();
    width = view.getWidth()
}

See this for more about the OnLayoutListener

like image 3
Gerard Avatar answered Oct 18 '22 04:10

Gerard