How to get height of LinearLayout
Asked Answered
P

3

13

I have a LinearLayout set height as match_parent as below:

<LinearLayout
    android:id="@+id/list_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

I want to get the height of this LinearLayout.
I used the code below:

LinearLayout ll_list = (LinearLayout)findViewById(R.id.list_layout);
int h = ll_list.getHeight();

But it return null.
How can I do?

Putnam answered 15/8, 2012 at 5:24 Comment(2)
unless you're going to have a background task optimizing bitmaps (or something similar) before showing them on the screen, I really can't thing on any moment any would need this value. If you could tell us a bit more about your application, we might be able to point you to a better design alternative.Beals
https://mcmap.net/q/234234/-get-height-and-width-of-a-layout-programmatically check this out, it may help you.Champac
E
43

First of all: your LinearLayout id is left_layout, not list_layout.

Also, ll_list.getHeight() will return 0 (as well as ll_list.getWidth()) if it's not drawed yet.

Solution would be to get the height after your view is layouted:

ll_list.post(new Runnable(){
    public void run(){
         int height = ll_list.getHeight();
    }
});

And make sure that your ll_list is final.

Effect answered 15/8, 2012 at 5:46 Comment(3)
@Putnam it's not your problem. Just make sure that you're calling getHeight() after view is drawed.Effect
@Putnam I've provided an exampleEffect
Is there any way to force android to draw the layout. I need the layout height in onCreateView().Gothurd
D
1
LinearLayout ll_list = (LinearLayout)findViewById(R.id.list_layout);
                                                       ^^^^^^^^^^
Democrat answered 15/8, 2012 at 5:40 Comment(2)
may be he typed wrong in the question. it wouldn't even compile if that was the caseCopal
see your xml file name and also change id and then check itDemocrat
N
1

You need to wait View to be initialized first use View Tree Observer it waits until the view is created check out this

get layout height and width at run time android

Noriega answered 5/7, 2017 at 11:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.