<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5"
android:text="Button1"
android:textSize="20dp" >
</Button>
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="Button2"
android:textSize="20dp" >
</Button>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="5"
android:text="Button1"
android:textSize="20dp" >
</Button>
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Button2"
android:textSize="20dp" >
</Button>
</LinearLayout>
在代码版本 1 中 按钮1的高度是按钮2的5倍
在代码版本 2 中 按钮2的高度是按钮1的5倍
当 android:layout_height="0dp"替换为 android:layout_height="match_patent"时,权重会反转。 您能否解释一下这种行为以及 android:layout_weights 的实际工作原理,并解释每种情况下的原因。
最佳答案
Layout_weight 设置为那些值被指定为 0 的组件。这意味着它们没有自己的高度/宽度,并且将占据屏幕重量的 %。
关于android:layout_weight 意外行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15681082/