Android布局管理详解(1)—— LinearLayout 线性布局

 Android的布局方式共有6种,分别是LinearLayout(线性布局)TableLayout(表格布局)FrameLayout(帧布局)RelativeLayout(相对布局)GridLayout(网格布局)以及AbsoluteLayout(绝对布局)

  本次主要介绍 LinearLayout 线性布局,其余布局留待以后介绍。

  线性布局由 LinearLayout 类来代表, LinearLayout 可以控制各组件横向或纵向排列。

  LinearLayout 常用属性介绍

  1.  android:orientation

    设置布局管理器内组件的排列方式,可设置为 horizon (水平排列)、vertical (垂直排列)。

    

复制代码
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="horizontal"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent">
 6     <Button
 7         android:id="@+id/btn1"
 8         android:layout_width="wrap_content"
 9         android:layout_height="wrap_content"
10         android:text="@string/btn1"/>
11     <Button
12         android:id="@+id/btn2"
13         android:layout_width="wrap_content"
14         android:layout_height="wrap_content"
15         android:text="@string/btn2"/>
16     <Button
17         android:id="@+id/btn3"
18         android:layout_width="wrap_content"
19         android:layout_height="wrap_content"
20         android:text="@string/btn3"/>
21 </LinearLayout>
复制代码

  上述代码设置了三个按钮(Button),第 3 行代码设置其排列方式为 horizon 水平排列,效果图如图 1: 

图 1 :                                                   图 2 :                                                图 3 :

                               

 将上述代码的第 3 行中 orientation 的值由 horizon 改为 vertical (如下代码),则按钮的排列方式变为垂直排列 ,如图 2

 

  View Code

   注意: Android 的线性布局不会换行,当组件一个挨着一个的排列到头之后,剩下的组件将不会被显示出来

  例:

  View Code

上述代码定义了 5 个按钮,使其水平排列,但其效果如上图 3 所示,只显示了四个按钮,第 5 个按钮没有被显示出来。

   2.  android:gravity

    设置布局管理器内组件的对齐方式,该属性值可设为 top(顶部对齐) 、bottom(底部对齐) 、left(左对齐) 、right(右对齐) 、center_vertical(垂直方向居中) 、 fill_vertical(垂直方向填充) 、 center_horizontal(水平方向居中) 、 fill_horizontal(水平方向填充) 、center(垂直与水平方向都居中) 、 fill (填充)、  clip_vertical(垂直方向裁剪) 、  clip_horizontal(水平方向裁剪) 。

    可同时指定多种对其方式的组合,中间用“|”连接,如下方代码设置对齐方式为 left|center_vertical 表示出现在屏幕左边且垂直居中,效果图如图 4 。

 

  View Code

   图 4 :

    

除以上两个常用属性外,LinearLayout 的属性还有以下几个:

  android:baselineAligned            该属性设为 false ,将会阻止该布局管理器与它的子元素的基线对其。

  android:divider                设置垂直布局时两个按钮直接的分隔条。

  android:measureWithLargestChild      该属性设为 true 时,所有带权重的子元素都会具有最大子元素的最小尺寸。

最后介绍一下 LinearLayout 子元素支持的常用属性:

  android:layout_gravity    指定该子元素在 LinearLayout 中的对其方式

  android:layout_weight    指定该子元素在 LinearLayout 中所占的权重

以上就是关于 android 布局中 LinearLayout 的介绍,如有疏漏或错误,欢迎指正。

  本文为博主原创文章,转载请在明显位置注明出处:

  原文地址 http://www.cnblogs.com/zzulihao

猜你喜欢

转载自blog.csdn.net/qq_36332133/article/details/79791463