在Android中,layout_weight是用來分配父容器中剩余空間的一個(gè)屬性。它通常與LinearLayout一起使用,用于在視圖中設(shè)置相對比例。
具體用法如下:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="3">
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="Text 1" />
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:text="Text 2" />
在上述示例中,子視圖1的權(quán)重為1,子視圖2的權(quán)重為2。因此,子視圖2將占據(jù)父容器中的兩倍空間。
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="Text 1" />
在上述示例中,子視圖1的寬度將根據(jù)其權(quán)重自動(dòng)調(diào)整,以填充父容器的剩余空間。
總結(jié):layout_weight用于在LinearLayout中設(shè)置子視圖的相對比例,使其根據(jù)權(quán)重自動(dòng)分配空間,以實(shí)現(xiàn)靈活的布局。它通常用于平均分配剩余空間或根據(jù)權(quán)重確定視圖的大小。