Android 如何获取 LinearLayout 的高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11964499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:19:47  来源:igfitidea点击:

How to get height of LinearLayout

androidandroid-linearlayout

提问by brian

I have a LinearLayout set height as match_parent as below:

我有一个 LinearLayout 设置高度为 match_parent 如下:

<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 的高度。
我使用了下面的代码:

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

But it return null.
How can I do?

但它返回空值。
我能怎么做?

回答by Dmitry Zaytsev

First of all: your LinearLayoutid is left_layout, not list_layout.

首先:您的LinearLayoutid 是left_layout,而不是list_layout

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

此外,如果尚未绘制,ll_list.getHeight()将返回 0(以及ll_list.getWidth())。

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_listis final.

并确保您的ll_listfinal.

回答by Samir Mangroliya

LinearLayout ll_list = (LinearLayout)findViewById(R.id.list_layout);
                                                       ^^^^^^^^^^

回答by Samir Mangroliya

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

您需要等待 View 被初始化,首先使用 View Tree Observer 它等待直到创建视图查看这个

get layout height and width at run time android

在运行时获取布局高度和宽度android