[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,显示效果如下图

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:paddingLeft="16dp"  
  6.     android:paddingRight="16dp"  
  7.     android:orientation="vertical" >  
  8.     <EditText  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:hint="@string/to" />  
  12.     <EditText  
  13.         android:layout_width="fill_parent"  
  14.         android:layout_height="wrap_content"  
  15.         android:hint="@string/subject" />  
  16.     <EditText  
  17.         android:layout_width="fill_parent"  
  18.         android:layout_height="0dp"  
  19.         android:layout_weight="1"  
  20.         android:gravity="top"  
  21.         android:hint="@string/message" />  
  22.     <Button  
  23.         android:layout_width="100dp"  
  24.         android:layout_height="wrap_content"  
  25.         android:layout_gravity="right"  
  26.         android:text="@string/send" />  
  27. </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 及下面的回复

0 0
原创粉丝点击