Android布局中 android:layout_weight 属性解释

定义:所有View(视图)元素中都有一个XML属性android:layout_weight,其值为0,1,2,3...等整数值。
使用了之后,其对应界面中的元素比例就会发生变化,变大或者变小。layout_weight属性其实就是一个元素重要度的属性,用于在线性布局中为不同的view元素设置不同的重要度。







<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<TextView android:id="@+id/a1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:layout_weight="1" />
<TextView android:id="@+id/a2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:layout_weight="2" />

</LinearLayout>

欢迎各位朋友,一起来讨论Android方面的技术难点。

android:layout_weight属性主要用来设置控件在屏幕上的位置空间,代码中如果第一个TextView中为1,第二个TextView为2,则这两个控件一个占总空间的1/3,

另一个占总空间的2/3。


在一个LinearLayout内各个组件是按weight值以正比形式显示在屏幕上 ,而在LinearLayout之间以反比的形式显示在屏幕上 ,很奇怪吧。




官方文档关于这个属性的解释

LinearLayout also supports assigning aweight to individual children. This attribute assigns an"importance" value to a view, and allows it to expand to fill anyremaining space in the parent view. Child views can specify aninteger weight value, and then any remaining space in the viewgroup is assigned to children in the proportion of their declaredweight. Default weight is zero. For example, if there are threetext boxes and two of them declare a weight of 1, while the otheris given no weight (0), the third text box without weight will notgrow and will only occupy the area required by its content. Theother two will expand equally to fill the space remaining after allthree boxes are measured. If the third box is then given a weightof 2 (instead of 0), then it is now declared "more important" thanboth the others, so it gets half the total remaining space, whilethe first two share the rest equally.

其实很简单,weight本来的意思就是重量,即 这个属性所代表的是重要程度,而不是比例

解释:
如果三个view水平排列,前两个view的wieght是1,第三个是默认值0,( 所有的视图都有一个layout_weight值,其默认值为0,)表示视图多大就占据多大的屏幕空间。可见第三个view的weight最低,那么第三个view就只会占用自己内容所需的宽度,剩下的宽度会被前两 个view平分。

如果第三个view的wieght是2,那么前两个view就会平分剩余的宽度,而第三个会(gets half the total) 占据所有空间的一半。

至于Linearlayout的weight属性越小的所占空间越多,我觉得这是因为Linearlayout的默认高度问题,一个简单的实验当我把两个Linearlayout的值设为1和5的时候,屏幕比例 依然不变,因为第一个Linearlayout的默认大小就是那么大


很乱,这个东西,不好解释。

更多相关文章

  1. Android(安卓)布局管理器
  2. RelativeLayout各个属性
  3. textView 和 edittext 的一些属性
  4. Android中RelativeLayout各个属性的含义
  5. TextView处理显示字数过长
  6. Android属性之build.prop,及property_get/property_set
  7. Android属性动画--基础使用
  8. 【Android(安卓)UI控件】EditText属性大全,TextView属性大全
  9. 安卓xml文件中设置动画匀速旋转无效?

随机推荐

  1. Android窗口跳转
  2. android 视频流的格式转换(YUV-RGB)
  3. Android中图形参数及图形内存信息获取
  4. Android使用URLConnection显示网络图片
  5. Android实现体重测量仪的源码
  6. android 线程学习
  7. Android的NDK开发(1)————Android(安
  8. android图形验证码
  9. Android(安卓)binder 实例
  10. 判断可用的intent和更改Drawable的透明度