linearlayout

LinearLayout的weight属性如何分配空间

小樊
81
2024-10-10 13:00:51
栏目: 云计算

在LinearLayout中,weight属性用于指定子视图在LinearLayout中所占的权重。当LinearLayout的宽度固定时,weight属性可以根据子视图的权重来分配空间。具体分配方式如下:

  1. 首先,为LinearLayout设置一个固定的宽度(例如android:layout_width="match_parent")。
  2. 为每个子视图设置weight属性,值为正数。例如,假设我们有两个子视图,一个宽度为100dp,另一个宽度为200dp,我们希望它们分别占据33%和67%的空间,那么可以将它们的weight属性设置为12

示例代码:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <View
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <View
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2" />

</LinearLayout>

在这个示例中,第一个子视图的宽度为100dp(1 * weight),第二个子视图的宽度为200dp(2 * weight)。由于LinearLayout的宽度固定为match_parent,所以子视图会根据权重分配空间。

0
看了该问题的人还看了