如何用android:layout_weight弄个满意的比例
在布局中android:layout_width 和 android:layout_height 一般会设为wrap_content和match_parent,当再设置android:layout_weight的时候,有时候就会出现混乱
例如:
两个TextView的都为 android:layout_width = “match_parent”
“One, One”TextView的android:layout_weight = “1”
“One, Two”TextView的android:layout_weight = “2”
预测结果:
“One, One”TextView占屏幕宽的1/3
“One, Two”TextView占屏幕宽的2/3
代码:
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="One,One"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="@+id/textView11"
android:background="@drawable/textview_border"
android:textColor="@android:color/white"
android:layout_marginLeft="3dp"
android:layout_marginRight="3dp"
android:gravity="center"
/>
<TextView
android:text="One,Two"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:id="@+id/textView12"
android:background="@drawable/textview_border"
android:textColor="@android:color/white"
android:layout_marginLeft="3dp"
android:layout_marginRight="3dp"
android:gravity="center"
/>
</LinearLayout>
实际结果:
分析:
android:layout_weight = “1” 的 “One, One”TextView占屏幕的2/3
android:layout_weight = “2” 的 “One, Two”TextView占屏幕的1/3
原因:
android:layout_weight的真实含义是:一旦View设置了该属性(假设有效的情况下),那么该 View的宽度等于原有宽度(android:layout_width)加上剩余空间的占比!
解释:
设屏幕宽度为L,在两个TextView的宽度都为match_parent的情况下,原有宽度为L,两个的TextView的宽度都为L,那么剩余宽度为L-(L+L) = -L
“One, One” TextView的weight设置占1/3,所以总宽度是L+(-L)*1/3 = (2/3)L.
“One, Two” TextView的weight设置占2/3,所以总宽度是L+(-L)*2/3 = (1/3)L.
- Google官方推荐,当使用weight属性时,将width设为0dip即可,效果跟设成wrap_content是一样的。这样weight就可以理解为占比了!