您的位置:首页 > 移动开发 > Android开发

Android线性布局(Linear Layout)

2016-05-06 16:26 423 查看
Android线性布局(Linear Layout)

LinearLayout是一个view组(view group),其包含的所有子view都以一个方向排列,垂直或是水平方向。我们能够用android:orientation属性来指定布局的方向。



图1

LinearLayout中所有的子view依次排列,所以垂直列表的每一行只有一个子view,而不管行有多宽。水平列表只有一个行高(行高由最高子view的高度+padding(填充)来决定)。LinearLayout关注子view之间的margins(边缘)和每个子view的gravity(对齐方式,右、中间或是左对齐)。

LinearLayout也支持用android:layout_weight属性为单个子view指定权重(weight)。这个属性为一个view指定一个非常重要的值,此值指定了该view需要占用屏幕上多大的空间。一个更大的权重值运行子view扩展到填充满其父view的剩余空间。子view能够指定权重值,然后view组中的剩余空间会按照声明的权重所占的比例来分配。默认的权重是0。

比如,如果有文本框(text field),其中两个声明权重为1,另一个没有指定权重(默认值为0)的文本框不会扩展,它只会占据它的内容所需要的区域。在所有这个三个文本框被测量后,其他两个文本框将平分剩余的空间。如果第3个文本框权重值为2,它就申明了自己比其他的文本框更重要,它占用了剩余空间的一半,另一半由那两个文本框平分。示例代码如下:

<?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>

还需要在LinearLayout\res\values\strings.XML文件中增加这些字符串的定义

<stringname="to">To</string>

<stringname="subject">Subject</string>

<stringname="message">Message</string>

<stringname="send">Send</string>

Activity中布局的效果如下图:



图2

为了更好去理解权重的意义,我们做一些修改,先来看下面一组权重值的效果:

(1) To=subject=0(权重),message=2,显示如下:



图3

由于to和subject编辑框的属性android:layout_height="wrap_content"表示它们要求其高度可以包住内容,而且android:layout_weight="0"(或者是不用这个属性),0表示需要显示多大的视图就占据多大的屏幕空间,所以to和subjec编辑框就只占用能包住它们内容的屏幕空间就可以了。那message编辑框的权重只要不是为0,那么它就占用除去to和subject编辑框占用的空间之外的空间。

(2) To=subject=1(权重),message=2,显示如下:



图4

虽然to和subject编辑框的属性android:layout_height="wrap_content",但因为它们的权重值为1(非零),则参与父view可用空间的分割,分割大小具体取决于每一个视图的layout_weight值以及该值在当前屏幕布局的整体 layout_weight值和在其它视图屏幕布局的layout_weight值中所占的比率而定,比如这里to和subject的权重值都为1,而message的为2,那么to和subject这两个view分别占用整个屏幕可用空间的1/4,而message占用2/4。

如果需要所有的子view大小一样,每个view的android:layout_height设置为0dp(对于垂直布局),或是每个view的android:layout_width设置为0dp(对于水平布局) ,然后设置每个view的android:layout_weight为1.

Android开发者Linear Layouts

http://developer.android.com/guide/topics/ui/layout/linear.html

Android布局---线性布局(Linear Layout)---别人翻译

http://www.2cto.com/kf/201301/183527.html

线性布局(Linear Layout)---理解应用

http://hi.baidu.com/justtmiss/item/a5b59909c688a6e4ff240dac

Android UI学习 -
Linear Layout,RelativeLayout

http://kb.cnblogs.com/page/73497/

/article/1440677.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: