Android五种布局管理器之『LinearLayout』

线性布局(LinearLayout)是Android五种布局中最简单的布局之一,它提供了控件水平或垂直排列的模型。同时,使用此布局时可以通过设置控件的weight参数来控制各个控件在容器内的相对大小。

LinearLayout布局的属性既可以在布局文件(XML)中设置,也可以通过成员方法进行设置。下面给出LinearLayout常用的属性及其对应属性设置的方法。

属性名称 对应方法 描述
android:orientationsetOrientation(int)设置线性布局的朝向,可取horizontal(水平)和vertical(垂直)两种排列方式
android:gravitysetGravity(int)设置线性布局的内部元素的布局对齐方式

线性布局中使用gravity属性来设置其内部子控件的对齐方式,当要为gravity设置多个值时,用“|”来分隔。gravity可取得值及其说明见下表:

属性值 说明
top不改变控件大小,对齐到容器顶部
bottom不改变控件大小,对齐到容器底部
left不改变控件大小,对齐到容器左侧
right不改变控件大小,对齐到容器右侧
center_vertical不改变控件大小,对齐到容器纵向中央位置
center_horizontal不改变控件大小,对齐到容器横向中央位置
center不改变控件大小,对齐到容器中央位置
fill_vertical若有可能,纵向拉伸以填满容器
fill_horizontal若有可能,横向拉伸以填满容器
fill若有可能,纵向横向同时拉伸以填满容器

下面来看一下效果:

点击放大图片

其中Main.xml代码如下:

 
 
 
 
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout  
  3.         xmlns:android="http://schemas.android.com/apk/res/android" 
  4.         android:orientation="vertical" 
  5.         android:gravity="center_horizontal" 
  6.         android:layout_width="fill_parent" 
  7.         android:layout_height="fill_parent" 
  8.     > 
  9.  
  10.         <LinearLayout android:orientation="vertical"  
  11.                       android:layout_width="fill_parent"  
  12.                       android:layout_height="fill_parent"  
  13.                       android:layout_weight="2"> 
  14.             <TextView android:text="Welcome to sunchis.com"  
  15.                       android:textSize="15pt"  
  16.                       android:layout_width="fill_parent"  
  17.                       android:layout_height="wrap_content" /> 
  18.         </LinearLayout> 
  19.  
  20.         <LinearLayout android:orientation="horizontal"  
  21.                       android:layout_width="fill_parent"  
  22.                       android:layout_height="fill_parent"  
  23.                       android:layout_weight="1"> 
  24.             <!-- 这里字水平居中  --> 
  25.             <TextView android:text="red"  
  26.                       android:gravity="center_horizontal"  
  27.                       android:background="#aa0000"  
  28.                       android:layout_width="wrap_content"  
  29.                       android:layout_height="fill_parent"  
  30.                       android:layout_weight="1"/> 
  31.  
  32.             <TextView android:text="green"  
  33.                       android:gravity="center_horizontal"  
  34.                       android:background="#00aa00"  
  35.                       android:layout_width="wrap_content"  
  36.                       android:layout_height="fill_parent"  
  37.                       android:layout_weight="1"/> 
  38.         </LinearLayout> 
  39. </LinearLayout> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值