[Android] 对android:layout_weight的一些解释
在Android线性布局LinearLayout中,android:layout_weight是一个比较有用的属性,用于指定当前控件在父控件中所占的比例。
1. 基本使用方法
以垂直vertical线性布局为例,将其中每个控件(也可以是子布局)的android:layout_height属性设置为"wrap_content",android:layout_weight属性设置一个数值(也可不设置,则相当于使用默认值0)。
这样实现的效果是:android:layout_weight属性为0的控件(或布局),按照其实际所需的大小为其分配垂直空间;剩余的android:layout_weight属性大于0的控件(或布局),按照各自属性值设置的比例来分配剩余的垂直空间。
下面的代码中显示了4个控件,只有第3个控件的android:layout_weight属性设置为1,显示效果如下图
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingLeft="16dp" android:paddingRight="16dp" android:orientation="vertical" > <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/to" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/subject" /> <EditText android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" android:gravity="top" android:hint="@string/message" /> <Button android:layout_width="100dp" android:layout_height="wrap_content" android:layout_gravity="right" android:text="@string/send" /></LinearLayout>
对于水平horizontal线性分布的用法类似。
2. 特殊问题的解释
上面提到的基本使用方法,将布局中控件(或子布局)的android:layout_height属性设置为"wrap_content",这是比较常用的属性值。
实际上,该属性设置为"fill_parent"也是可以的,但这样的话,我们会发现实际显示的控件大小比例与我们设想的不太一样,android:layout_weight属性值较大的显示出来反而较小。
参考资料[2]下面的回复,这里只贴出一个公式供大家参考。更详细的演示大家可以在资料[2]中看到。
假设android:layout_height属性大于0的控件(子布局)有n个,其值分别为a1,a2,……,an,这些值的和为A,则各个控件实际所占的比例可用如下公式求出:
portion[i]=1+(1-n)*ai/A
3. 文本框中文字长度过长,导致控件不能按设定的比例显示。
将基本使用方法中,android:layout_height属性由"wrap_content"改为"0dp"。更改前后的效果如下面两图[2]
android:layout_height="wrap_content"
android:layout_height="0dp"
参考资料:
[1]http://developer.android.com/guide/topics/ui/layout/linear.html
[2]http://blog.sina.com.cn/s/blog_7cd0c0a80100zmfe.html 及下面的回复
更多相关文章
- android layout属性介绍
- “加一”项目总结--android使用篇(二)(转)
- Android中如何解决输入法键盘和activity页面遮挡的问题
- android使用android:ellipsize="end"无效的解决方法
- android layout属性介绍
- Android:TextView属性
- TextView常用属性
- EditText的常用属性和实例
- android layout物业介绍