【问题标题】:Fill remaining space: LinearLayout and weight or RelativeLayout?填充剩余空间:LinearLayout 和权重还是RelativeLayout?
【发布时间】:2015-12-01 06:25:33
【问题描述】:

如果我有 2 个视图,我希望一个占用必要的空间,另一个占用剩余的空间,我应该怎么做?

假设我想垂直放置视图。下面的视图应该占用必要的空间(wrap_content),上面的视图应该占用容器布局的剩余空间。

我用过这两种解决方案(简化代码):

1) LinearLayoutweight

<LinearLayout ...>
  <View height="0dp" weight="1" .../>
  <View height="wrap_content" .../>
</LinearLayout>

2) RelativeLayout 对齐

<RelativeLayout ...>
  <View height="wrap_content"    id="@+id/big" alignParentTop .../>
  <View height="wrap_content" below="@+id/big" alignParentBottom .../>
</RelativeLayout>

LinearLayout 方法始终有效,RelativeLayout 通常按预期工作,但这显然是模棱两可的,因为没有人说@+id/big 视图应该大于下面的视图。

我认为第一种方法更好,因为它不是模棱两可的。但是,我已经看到了很多关于第二种方法的示例和答案。

对于这些情况,您使用什么解决方案。有最佳做法吗?

谢谢!

编辑

接受Touf 的回答,现在我会这样做(注意match_parent):

<RelativeLayout ...>
  <View height="match_parent"    id="@+id/big" alignParentTop .../>
  <View height="wrap_content" below="@+id/big" alignParentBottom .../>
</RelativeLayout>

【问题讨论】:

    标签: android layout


    【解决方案1】:

    我会使用相对布局:

    <View height="match_parent"    id="@+id/big" android:layout_above="@+id/view2" alignParentTop ... >
    
    <View height="wrap_content" id="@+id/view2" alignParentBottom ...>
    

    这样第一个视图将填充屏幕高度,直到它到达第二个视图。

    【讨论】:

    • 谢谢,有道理,虽然我不知道为什么 android 将“fill_parent”更改为“match_parent”。我的意思是,使用旧的大小限定符,您的解决方案将非常清楚:“尽可能多地填充父级”。新尺寸似乎在说“与父尺寸匹配”。
    • "fill_parent" 和 "match_parent" 是一样的。查看这些链接:stackoverflow.com/questions/10854717/…developer.android.com/reference/android/view/…
    • 顺便说一句,我想我只需要使用“上方”或“下方”即可;两者都使用是多余的,不是吗?也许我应该使用下面来引用之前声明的视图,尽管我不确定是否可以使用前向引用(引用之后在 xml 中声明的视图)。
    • 是的,很抱歉,下面不需要=“@+id/big”,它是多余的,我忘了删除它。
    • 但是如何为 firstview 设置 minHeight。我尝试了 minHeight 属性但没有工作。第二个视图完全填满了屏幕(如果它的高度太大)。
    猜你喜欢
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2015-04-14
    • 2013-03-12
    • 2021-02-06
    • 1970-01-01
    相关资源
    最近更新 更多