android 代码设置weight
时间: 2023-12-14 16:03:17 浏览: 30
在 Android 中,可以使用 `android:layout_weight` 属性来设置 View 的权重。这个属性用于在布局中设置 View 的相对大小,比如在 LinearLayout 中,可以使用 `android:layout_weight` 来让 View 按比例分配剩余空间。
下面是一个示例代码,演示如何使用 `android:layout_weight` 属性:
```
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 1"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Button 2"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:text="Button 3"/>
</LinearLayout>
```
在这个例子中,我们创建了一个水平方向的 LinearLayout,并在其中添加了三个 Button。每个 Button 的宽度都设置为 0dp,然后设置了一个不同的权重。第一个 Button 的权重为 1,第二个 Button 的权重为 2,第三个 Button 的权重为 3。这意味着第一个 Button 将占据总宽度的 1/6,第二个 Button 将占据总宽度的 2/6,第三个 Button 将占据总宽度的 3/6。