欢迎来到人人都可写代码,大家好,我是杨晓华,今天我们的课程内容是:Android界面布局中的线性布局。
1、LinearLayout的常用属性
orientation: 布局中组件的排列方式,有horizontal水平,vertical(垂直,默认)两种方式。
gravity: 控制组件所包含的子元素的对齐方式,可多个组合(如:buttom | left)。
layout_gravity: 控制该组件在父容器里的对齐方式。
layout_width: 布局的宽度,用wrap_content(组件实际大小),fii_parent或match_parent填满父容器。
layout_height: 布局的高度,参数和宽度的一样。
id: 为该组件设置一个资源id,在activity文件中可通过findViewById找到该组件。
background: 为该组件设置一个背景图片或用颜色覆盖。
divider:该属性用于为线性布局设置分割线图片,通过showDividers来设置分割线的所在位置,有四个可选值:none,middle,beginning,end。
2、权重weight使用介绍
(1)如果android:layout_weight="1"时,通过设置控件的layout_weight属性以控制各个控件在布局中的相对大小,线性布局会根据该控件layout_weight值与其所处布局中所有控件layout_weight值之和的比值为该控件分配占用的区域。
(2)例如:在水平布局的LinearLayout中有4个TxtView,这4个TextView的layout_weight属性值都为1,那么这4个TextView的大小将拉伸到总大小的四分之一。
(3)如果layout_weight指为0,控件会按原大小显示,不会被拉伸;对于其余layout_weight属性值大于0的控件,系统将会减去layout_weight属性值为0的控件的宽度或者高度,再用剩余的宽度或高度按相应的比例来分配每一个控件显示的宽度或高度。
3、举例说明
(1)实现的布局效果:
![167b3391c71eb40119e37a0451e2d94e.png](https://i-blog.csdnimg.cn/blog_migrate/06e13eaf5c8cbb885d1392de3b04df64.png)
(2)对应的布局代码:
<?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:orientation="vertical" >
<!-- 垂直布局 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_weight="1"
android:orientation="vertical"
>
<TextView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"
android:background="#ff0000"
/>
<TextView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"
android:background="#00ff00"
/>
<TextView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"
android:background="#0000ff"
/>
</LinearLayout>
<!-- 水平布局 -->
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_weight="2"
>
<TextView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"
android:background="#ff0000"
/>
<TextView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"
android:background="#00ff00"
/>
<TextView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"
android:background="#0000ff"
/>
<TextView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"
android:background="#c0c0c0"
/>
</LinearLayout>
</LinearLayout>
开头:人人都可写代码-Android零基础编程-序言-01
下一篇:人人都可写代码-Android零基础编程-表格布局10