【问题标题】:How to get height of LinearLayout如何获取LinearLayout的高度
【发布时间】:2017-07-05 19:45:04
【问题描述】:

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

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

我想获取此 LinearLayout 的高度。
我使用了下面的代码:

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

但它返回 null。
我能怎么做?

【问题讨论】:

  • 除非你在屏幕上显示位图(或类似的东西)之前有一个后台任务优化位图,否则我真的无法在任何时候需要这个值。如果您能告诉我们更多关于您的应用程序的信息,我们或许可以为您指出更好的设计替代方案。
  • stackoverflow.com/a/41705445/5664529 看看这个,它可能对你有帮助。

标签: android android-linearlayout


【解决方案1】:

首先:您的LinearLayout id 是left_layout,而不是list_layout

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

解决方案是在布局视图后获取高度:

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

并确保您的ll_listfinal

【讨论】:

  • @brian 这不是你的问题。只需确保在绘制视图后调用 getHeight()
  • @brian 我提供了一个例子
  • 有没有办法强制android绘制布局。我需要 onCreateView() 中的布局高度。
【解决方案2】:
LinearLayout ll_list = (LinearLayout)findViewById(R.id.list_layout);
                                                       ^^^^^^^^^^

【讨论】:

  • 可能是他在问题中输入错误。如果是这样,它甚至不会编译
  • 查看您的 xml 文件名并更改 id 然后检查它
【解决方案3】:

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

get layout height and width at run time android

【讨论】:

    猜你喜欢
    • 2014-06-30
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多