Android开发学习教程(12)- Android布局之线性布局LinearLayout

84 阅读2分钟

—— 当下的生活或许疲惫又难熬,但你要相信,始终没有放弃过的你,一定会过上想要的生活。

上一篇我们讲了对话框AlertDialog的基本用法,这里来学习常用布局之线性布局的基本用法。

线性布局是什么

线性布局中的控件按照横向或竖向排列,并且线性布局不会换行,当控件超出屏幕边缘,后面的控件就被隐藏,不会被显示出来。

线性布局有什么用

控制其中的控件只能横向或竖向排列。

线性布局怎么用

继续基于上一篇的项目,我们新建一个LinearLayoutActivity:

123456789101112131415161718192021222324252627282930313233<?``xml version``=``"1.0" encoding``=``"utf-8"``?>``<``LinearLayout xmlns:android``=``"http://schemas.android.com/apk/res/android"``    ``android:layout_width``=``"match_parent"``    ``android:layout_height``=``"match_parent"``    ``android:gravity``=``"center"``    ``android:orientation``=``"horizontal"``>``    ``<``TextView``        ``android:layout_width``=``"wrap_content"``        ``android:layout_height``=``"wrap_content"``        ``android:text``=``"Hello 我是第一个子控件" />``    ``<``TextView``        ``android:layout_width``=``"wrap_content"``        ``android:layout_height``=``"wrap_content"``        ``android:text``=``"Hello 我是第二个子控件" />``    ``<``TextView``        ``android:layout_width``=``"wrap_content"``        ``android:layout_height``=``"wrap_content"``        ``android:text``=``"Hello 我是第三个子控件" />``    ``<``TextView``        ``android:layout_width``=``"wrap_content"``        ``android:layout_height``=``"wrap_content"``        ``android:text``=``"Hello 我是第四个子控件" />``    ``<``TextView``        ``android:layout_width``=``"wrap_content"``        ``android:layout_height``=``"wrap_content"``        ``android:text``=``"Hello 我是第五个子控件" />``</``LinearLayout``>

Android开发学习教程(12)- Android布局之线性布局LinearLayout

上图横向排列了五个控件,并且线性布局不会自动换行,当控件超出屏幕边缘,后面的控件就被隐藏,不会被显示出来。

LinearLayout基本属性

android:gravity:用来控制子控件的位置,值有top,left,right,bottom,center,分别表示子控件在顶部、左部、右部、下部、垂直方向居中并且水平方向居中,值得注意的是,还可以组合取值,如right|center_vertical表示子控件在右部并且垂直方向居中;

android:orientation:用来控制子控件的排列方式,值为horizontal时表示所有子控件横向排列,为vertical时表示所有子控件竖向排列,上面的例子是横向排列,我们来试试竖向排列;

把android:orientation改为vertical,为了使效果更明显,我们去掉android:gravity设置,使用默认值(top|left),运行如下:

Android开发学习教程(12)- Android布局之线性布局LinearLayout