提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
为了适应不同的界面风格,Android提供了4种常用布局,分别是线性布局,相对布局,表格布局,帧布局。这四种布局都直接或者间接的继承了ViewGroup,因此这四种布局都可以在ViewGroup容器中定义属性。
一、界面布局的通用属性
因为Android提供的4种布局都继承自ViewGroup,所以他们都有一些通用属性。下面一张表来列出这些通用属性。
属性名称 | 功能描述 |
---|---|
android:id | 设置布局标识 |
android:layout_width | 设置布局宽度 |
android:layout_height | 设置布局高度 |
android:background | 设置布局背景 |
android:layout_margin | 设置当前布局与屏幕边界、周围布局或控件的距离 |
android:padding | 设置当前布局与该布局中控件的布局 |
1.android:id
用于设置当前布局的唯一标识。在xml布局文件中他的属性值是通过"@+id/属性名称'定义的。为布局指定android:id属性后,在R.java文件中会自动生成相应的 int 值。在Java代码中通过findViewById()方法传入该int 值来获取布局对象。
2.android:layout_width
用于设置布局的宽度,可以自己设置具体的尺寸(eg:30dp),也可以是系统定义的值。
值 | 功能描述 |
---|---|
fill_parent | 宽度与父容器宽度相同 |
match_parent | 宽度与父容器宽度相同,从Android2.2.0开始推荐使用match_parent |
warp_content | 宽度恰好能包裹它的内容 |
3.android:layout_height
用于设置布局的高度,可以自己设置具体的尺寸(eg:25dp),也可以是系统定义的值。
值 | 功能描述 |
---|---|
fill_parent | 高度与父容器高度相同 |
match_parent | 高度与父容器高度相同,从Android2.2.0开始推荐使用match_parent |
warp_content | 高度恰好能包裹它的内容 |
4.android:background
用于设置布局背景,值可以设置为颜色也可以是图片。
5.android:layout_margin
设置当前布局的外边距,属性值为具体的尺寸(eg:25dp)。也可以分别为上下左右设置边距。
android:layout_marginTop :为上外边距设置值
android:layout_marginBottom :为下外边距设置值
android:layout_marginLeft : 为左外边距设置值
android:layout_marginRight : 为右外边距设置值
6.android:padding
设置当前布局的内边距,属性值为具体的尺寸。也可以分别为上下左右设置边距。
android:paddingTop : 为上内边距设置值
android:paddingBottom : 为下内边距设置值
android:paddingLeft : 为左内边距设置值
android:paddingRight : 为右内边距设置值
二、线性布局
容器里面的控件被水平或垂直排列。
在xml布局文件中定义LinewarLayout的基本语法格式:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
属性="属性值"
属性="属性值"
......>
容器中的控件
</LinearLayout>
除了布局的通用属性,LinearLayout还有两个比较常用的属性:
属性名称 | 功能描述 |
---|---|
android:orientation | 设置布局内控件的排列顺序 |
android:layout_weight | 在布局设置控件权重,属性值可直接写int值 |
1.android:orientation
设置LinearLayout中控件的排列顺序,其可选值为vertical和horizontal
vertical:LinearLayout中控件从上到下竖直排列。
horizontal:LinearLayout中控件从左到右水平排列。
2.android:layout_weight
这个属性称为权重,通过设置该属性,可使布局内的控件按照权重比来显示大小,在进行屏幕适配时起到关键作用。
三、相对布局
相对布局通过定位的方式指定子控件的位置。通过<RelativeLayout>标签定义,基本格式如下:
<RelativeLayout
属性="属性值"
......>
控件....
</RelativeLayout>