天天看点

LinearLayout之weight完美详解

LinearLayout之weight详解

公式: 计算高度或宽度=原来高度或宽度 + (LinearLayout的高度或宽度 - 所有组件高度或宽度之和)*(当前组件weight/所有weight之和)

举3个简单的例子

例1, <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <View android:id="@+id/view1" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="2" android:background="#fff000" /> <View android;id="@+id/view2" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="3" android:background="#000fff" /> </LinearLayout>

这个的应该很清楚。view1 和view2 在LinearLayout中分别占全部LinearLayout的2/5和3/5. 套一下公式, LInearLayout 高度是 L view1的高度 = 0dp + (L - (0+0) ) * ( 2/ (2+3) ) = 2/5L view2的高度 = 0dp + (L - (0+0) ) * ( 3/ (2+3) ) = 3/5L

例2 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <View android:id="@+id/view1" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="2" android:background="#fff000" /> <View android;id="@+id/view2" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="3" android:background="#000fff" /> </LinearLayout> 套一下公式, LInearLayout 高度是 L LinearLayout中字控件高度写成match_parent,计算高度时,会有和父控件一样的高度。 view1的高度 = L + (L - (L+L) ) * ( 2/ (2+3) ) = 3/5L view2的高度 = L + (L - (L+L) ) * ( 3/ (2+3) ) = 2/5L

此处应该有掌声~

例3 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <View android:id="@+id/view1" android:layout_width="wrap_content" android:layout_height="30dp" android:layout_weight="2" android:background="#fff000" /> <View android;id="@+id/view2" android:layout_width="wrap_content" android:layout_height="40dp" android:layout_weight="3" android:background="#000fff" /> </LinearLayout> 套一下公式, LInearLayout 高度是 L。 view1的高度 = 30dp + (L - (30dp+40dp) ) * ( 2/ (2+3) ) = 30dp + (L - 70dp) *2/5 = 2/5 L + 2dp view2的高度 = 40dp + (L - (30dp+40dp) ) * ( 3/ (2+3) ) = 40dp + (L - 70dp) *3/5 = 3/5 L - 2dp

至此,我们可以准确掌握各种情况各种值的weight效果了!

此处应该有掌声