【问题标题】:How can I get wrap_content or match_parent layout width and height in android?如何在 android 中获取 wrap_content 或 match_parent 布局宽度和高度?
【发布时间】:2017-04-03 03:16:35
【问题描述】:

我想在某些 android 设备中获取我的布局或视图(不是屏幕大小)宽度和高度,那么我该怎么做呢?例如:

<LinearLayout
     android:orientation="vertical"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:layout_weight="1"
     android:paddingRight="8dp"
     android:paddingLeft="8dp"
     android:id="@+id/layout_scrol_left"/>

我有这个布局,我想在运行时获取布局宽度和高度大小(倾角),我该怎么做?

【问题讨论】:

  • 我的问题不同,我想在运行时获取我的视图或布局大小,而不是屏幕大小

标签: android height width


【解决方案1】:

我认为你可以使用类似的东西

    LinearLayout myView =(LinearLayout)findViewById(R.id.layout_scrol_left);

在调整 UI 线程的大小和布局后,您可以使用以下方法

    myview.getHeight();
    myview.getWidth();

希望这会有所帮助。

如果您在使用上述方法时遇到问题,请查看getWidth() and getHeight() of View returns 0

【讨论】:

  • 上面的代码应该可以解决问题,但是,不要太早调用它(例如 onCreate),因为必须首先调整 UI 的大小和布局。查看stackoverflow.com/questions/3591784/… 了解更多信息
  • 它不起作用。 myview.getHeight 和 myview.getWidth() =0
  • 我认为您调用它为时过早,您应该在 UI 线程调整大小和布局后使用它。看看上面@fbwnd给出的链接
【解决方案2】:

首先你需要进行布局。

LinearLayout ll_left = (LinearLayout)findViewById(R.id.layout_scrol_left);

现在如果 ll_left 尚未绘制,则 ll_left.getHeight() 和 ll_left.getWidth() 都将返回 0。

所以你必须在你的视图被绘制之后得到它们:

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

【讨论】:

  • 没问题。如果有帮助记得标记答案。
猜你喜欢
  • 1970-01-01
  • 2022-08-14
  • 1970-01-01
  • 1970-01-01
  • 2012-08-17
  • 2013-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多