Android LinearLayout布局问题

layout_gravity

在“某些时候”,layout_gravity这个属性不好使了,失去了它应有的作用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<EditText
android:id="@+id/edit_msg"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<Button
android:id="@+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="发送" />
</LinearLayout>

上述代码的目的,就是让按钮靠右边。我增加了一个属性

1
<android:layout_gravity="right">

layout_gravity 表示组件自身在父组件中的位置
gravity 表示组件的子组件在组件中的位置

看似很简单嘛,问题究竟出在哪里了呢?

  • 当作为父layout的LinearLayout的属性为android:orientation=”vertical” 的时候。android:layout_gravity=”?”这里设为横向的时候才能生效。比如:left,right,center_horizontal等;
  • 当作为父layout的LinearLayout的属性为android:orientation=”horizental” 的时候。android:layout_gravity=”?”这里设为纵向的时候才能生效。比如:top,bottom,center_vertical等;
  • 有一个比较特殊的是center,不管是横向还是纵向的时候,它总有一个方向起作用, 因为LinearLayout他只可能有一个方向。

layout_weight

linearLayout自适应布局的问题,我想在一行里,先放个文本框,再放个固定宽度的按钮,文本框宽度填满剩余的空间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<EditText
android:id="@+id/edit_msg"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<Button
android:id="@+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送" />
</LinearLayout>

但是发现Button不能显示出来,这个时候我们需要设置layout_weight="1"

1
2
3
4
5
<EditText
android:id="@+id/edit_msg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>

LinearLayout 中的控件可以添加 layout_weight 属性。LinearLayout 在分配空间时会先分配没有设置 Weight 的元素,然后对当前剩余空间按Weight比例分配给设置了 Weight 的元素。

这个属性可以很好的应对那些内容会动态变化的布局结构。