我相信大家在布局文件中都用过权重(layout_weight)吧,当然这只有在线性布局(Linearlayout)中才有的,可是很多人也许都只是简单的理解为比。
其实权重就是:
把屏幕剩余空间按比例分配
大家先记住这句话,这里就来深入理解下权重,这里以水平排列为例(即宽度的权重),懂了水平的,竖直排列的(即高度的权重)自然同理。
①第一种情况(宽度为wrap_content):
a.
<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="horizontal"
tools:context="com.example.weight.MainActivity" >
<Button
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="btn1" />
<Button
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="btn2" />
</LinearLayout>
效果:
现在两个按钮的宽度都为wrap_content,所以剩下的屏幕宽度为:
math_parent - 2*wrap_content,权重为1:1
则btn1所占宽度为:本身宽度 + 剩下屏幕的宽度的1/2 = wrap_content
+ 1/2(math_parent - 2*wrap_content)
btn2所占的宽度为:本身宽度 + 剩下屏幕的宽度的1/2 = wrap_content
+ 1/2(math_parent - 2*wrap_content)
从上面看到两式相等,所以两个按钮应该是平分整个屏幕宽度
b.
<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="horizontal"
tools:context="com.example.weight.M