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
How to get height of 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 LinearLayout
id is left_layout
, not list_layout
.
首先:您的LinearLayout
id 是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_list
is final
.
并确保您的ll_list
是final
.
回答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 它等待直到创建视图查看这个