[Android] 对android:layout_weight的一些解释
来源:互联网 发布:大苗医考网官网网络班 编辑:程序博客网 时间:2024/04/29 12:52
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] 对android:layout_weight的一些解释
- [Android] 对android:layout_weight的一些解释
- android:layout_weight 用法解释
- Android布局属性Layout_weight的标准解释
- Android LinearLayout layout_weight的几点解释
- android:layout_weight的一些疑惑的地方
- 对android的layout_weight属性的理解
- 对android的layout_weight属性的理解
- 对android:layout_weight设置的详解
- android UI 之layout_weight 的解释及使用
- Android中 android:layout_weight 属性 完美解释
- Android中 android:layout_weight 属性 完美解释
- Android中 android:layout_weight 属性 完美解释
- Android中 android:layout_weight 属性 完美解释
- Android 对Layout_weight属性…
- android 中xml对RelativeLayout设置的一些参数解释
- Android:layout_weight的用法
- android:layout_weight的作用
- 2014年中科院地理所博士考试真题-地理信息系统
- Android中RelativeLayout各个属性的含义
- Java对日期Date类进行加减运算,年份加减,月份加减
- 【C语言学习】链接
- 【Android核心基础08】 - Service
- [Android] 对android:layout_weight的一些解释
- 星星
- SVN:回滚代码
- 【Android】android ndk r10 环境配置
- StringBuffer的equals
- hdu1232并查集
- opencv对bmp格式图片的封装使用
- R语言文件操作
- UVa10622 Perfect P-th Powers