我有一个包含3个按钮的LinearLayout
(水平方向)。我希望3个按钮有一个固定的宽度,并均匀分布在LinearLayout
的宽度上。
我可以通过将LinearLayout
的重力设置为居中,然后调整按钮的填充来实现这一点,但这种方法适用于固定宽度,不适用于不同的设备或方向。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/btnOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="120dp" />
<Button
android:id="@+id/btnTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="120dp" />
<Button
android:id="@+id/btnThree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="120dp" />
</LinearLayout>
发布于 2010-08-13 02:24:23
在fedj's answer上展开,如果将layout_width
设置为0dp
,并将每个按钮的layout_weight
设置为1,则可用宽度将在按钮之间平均共享。
发布于 2013-01-03 00:46:58
如果您不希望按钮缩放,但希望调整按钮之间的间距(所有按钮之间的间距相等),您可以使用weight=为“1”的视图,它将填充按钮之间的空间:
<Space
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_weight="1" >
</Space>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="@null"
android:gravity="center_horizontal|center_vertical"
android:src="@drawable/tars_active" />
<Space
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_weight="1" >
</Space>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="@null"
android:gravity="center_horizontal|center_vertical"
android:src="@drawable/videos_active" />
<Space
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_weight="1" >
</Space>
发布于 2015-05-12 23:10:39
为此,可以将View
的layout_width
设置为0dp
,并将layout_weight
设置为1
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<TextView
android:layout_width="0dp"
android:text="example text"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
安卓layout_weight的工作方式是:
首先,它查看视图通常占用的大小,并保留此space.
match_parent
,则它会将剩余的空间除以 layout_weight
s的比例。因此,如果您为视图layout_weight="2"
layout_weight="1"
,结果比率将为2: 1,即:第一个视图将获得剩余空间的2/3,另一个视图将获得1/3的空间。<>F219layout_weight>这就是为什么如果将layout_width
的大小设置为0dp
,那么第一步没有额外的意义,因为两个视图都没有分配任何空间。然后,只有第二个点决定每个View
获得的空间,从而根据比率为View
提供您指定的空间!
通过提供一个显示相反情况的示例来解释为什么 0dp
导致空间均匀划分:下面的代码将产生一些不同的结果,因为example text
现在的宽度大于0dp
,因为它有wrap_content
,而不是使剩余的空闲空间划分小于100%,因为文本占用了空间。结果是他们得到了50%的空闲空间,但是文本已经占用了一些空间,所以TextView
的将远远超过总空间的50%。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<TextView
android:layout_width="wrap_content"
android:text="example text"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
https://stackoverflow.com/questions/3470420
复制相似问题