在学习 Android 开发时,在看到官网的一个线性布局例子Linear Layout tutorial,通过指定android:layout_weight的值来改变子视图在布局中占用的比例大小,发现运行结果与自己写的相反。到底哪里忽略了呢?直接上代码。
结果分析:
嗯哼,例子中使用LinearLayout垂直布局,有两个文本视图控件,它们除了颜色和文本不同之外,layout_weight属性也不同。但官方的Linear Layout tutorial例子中,将控件的layout_weight更改得出的结果刚好相反,应该是weight值越大的占的空间越大才对吧。先看下官方例子中修改过后的代码和结果:
< ?xml version="1.0" encoding="utf-8"?>
运行结果:
结果分析:
嗯哼,例子中使用LinearLayout垂直布局,有两个文本视图控件,它们除了颜色和文本不同之外,layout_weight属性也不同。但官方的Linear Layout tutorial例子中,将控件的layout_weight更改得出的结果刚好相反,应该是weight值越大的占的空间越大才对吧。先看下官方例子中修改过后的代码和结果:
< ?xml version="1.0" encoding="utf-8"?>
修改layout_weight后的运行结果:
问题原因
没错,结果相反了,在自己写的Demo中,weight值较大的视图反而变小了。仔细对比代码发现,原来文本视图中的高度属性被我设置成"fill_parent",将它们改为"wrap_content"之后,再次运行结果:
总结
layout_weight 属性在文档中的定义/LinearLayout.LayoutParams.html#attr_android:layout_weight Indicates how much of the extra space in the LinearLayout will be allocated to the view associated with these LayoutParams. Specify 0 if the view should not be stretched. Otherwise the extra pixels will be pro-rated among all views whose weight is greater than 0.也即是说,weight是定义独立子视图的权重比例属性,表示占用父视图的剩余空间的比例,默认值为0。 还需要注意的是,在同一个LinearLayout中的各个元素之间的 weight 是正向比例的,但是如果是各个LinearLayout之间的 weight 则是反向的。

