Android五种布局管理器之『LinearLayout』
16lz
2021-01-25
线性布局(LinearLayout)是Android五种布局中最简单的布局之一,它提供了控件水平或垂直排列的模型。同时,使用此布局时可以通过设置控件的weight参数来控制各个控件在容器内的相对大小。
LinearLayout布局的属性既可以在布局文件(XML)中设置,也可以通过成员方法进行设置。下面给出LinearLayout常用的属性及其对应属性设置的方法。
属性名称 | 对应方法 | 描述 |
android:orientation | setOrientation(int) | 设置线性布局的朝向,可取horizontal(水平)和vertical(垂直)两种排列方式 |
android:gravity | setGravity(int) | 设置线性布局的内部元素的布局对齐方式 |
线性布局中使用gravity属性来设置其内部子控件的对齐方式,当要为gravity设置多个值时,用“|”来分隔。gravity可取得值及其说明见下表:
属性值 | 说明 |
top | 不改变控件大小,对齐到容器顶部 |
bottom | 不改变控件大小,对齐到容器底部 |
left | 不改变控件大小,对齐到容器左侧 |
right | 不改变控件大小,对齐到容器右侧 |
center_vertical | 不改变控件大小,对齐到容器纵向中央位置 |
center_horizontal | 不改变控件大小,对齐到容器横向中央位置 |
center | 不改变控件大小,对齐到容器中央位置 |
fill_vertical | 若有可能,纵向拉伸以填满容器 |
fill_horizontal | 若有可能,横向拉伸以填满容器 |
fill | 若有可能,纵向横向同时拉伸以填满容器 |
下面来看一下效果:
其中Main.xml代码如下:
view plain copy
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:gravity="center_horizontal"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <LinearLayoutandroid:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_weight="2">
- <TextViewandroid:text="Welcometosunchis.com"
- android:textSize="15pt"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"/>
- </LinearLayout>
- <LinearLayoutandroid:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_weight="1">
- <!--这里字水平居中-->
- <TextViewandroid:text="red"
- android:gravity="center_horizontal"
- android:background="#aa0000"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_weight="1"/>
- <TextViewandroid:text="green"
- android:gravity="center_horizontal"
- android:background="#00aa00"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_weight="1"/>
- </LinearLayout>
- </LinearLayout>
更多相关文章
- 【Android(安卓)UI设计与开发】第06期:底部菜单栏(一)使用TabActivi
- android 4.2的新特性layoutRtl,让布局自动从右往左显示
- Android中用seekbar控件控制歌曲的进度
- Android(安卓)图片控件ImageView
- 分享五种Android常用布局方式
- 第16章、布局Layouts之GridLayout网格布局(从零开始学Android)
- Android(安卓)真机布局查看
- Android自定义相机镂空遮罩
- android简单网页浏览器的开发