Nothing

Android布局

2024/10/01

布局格式

线性布局LinearLayout

线性布局(LinearLayout)主要以水平或垂直方式来排列界面中的控件。并将控件排列到一条直线上。在线性布局中,如果水平排列,垂直方向上只能放一个控件,如果垂直排列,水平方向上也只能方一个控件。

使用线性布局,需要将布局节点改成LinearLayout,基本格式如下:

1
2
3
4
5
6
7
8
9
10
11
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
....

</LinearLayout>

LinearLayout常用属性

orientation

在线性布局中,控件排列有水平和垂直两个方向,控件排列方向由android:orientation属性来控制,该属性需要加在LinearLayout标记的属性中。将orientation属性值设置成为horizontal,控件将从水平方向从左往右排列,将orientation属性值设置成为vertical控件将从垂直方向从上往下排列。

gravity属性

线性布局的控件默认是从左往右排列或从上往下排列,如果想让线性布局中的控件排列对齐右边缘或者底部,可以用gravity属性控制。不过该属性值并不是只有在LinearLayout中才能使用,其他的布局用该属性同样能生效。

layout_weight属性

LinearLayout中另外一个常用的属性是layout_weight,该属性需要加在LinearLayout的子控件中。其作用是分配线性布局中的剩余空间到该控件上。

如下图所示,在控件没有添加layout_weight属性时,控件未占满线性布局的区域会空出来。

layout_margin属性

margIn属性设置当前控件与上级控件之间的间距,及子控件与父控件之间的距离,通常使用bp等单位标注具体间隔

padding属性

相应的,padding属性用于设置当前控件与同级控件之间的间距,用法与margin属性用法类似

相对布局RelativeLayout

相对布局(重点):相对布局是通过相对定位的方式让控件出现在布局任意位置;

在相对布局中如果不指定控件摆放的位置,那么控件都会被默认放在RelativeLayout的左上角。因此要先指定第一个控件的位置,再根据一个控件去给其他控件布局。

RelativeLayout常见属性

相对于父元素给控件布局
android:layout_centerHrizontal 水平居中
android:layout_centerVertical 垂直居中
android:layout_centerInparent 相对于父元素完全居中
android:layout_alignParentBottom 位于父元素的下边缘
android:layout_alignParentLeft 位于父元素的左边缘
android:layout_alignParentRight 位于父元素的右边缘
android:layout_alignParentTop 位于父元素的上边缘
android:layout_alignWithParentIfMissing 如果对应的兄弟元素找不到的话就以父元素做参照物

属性值必须为id的引用名“@id/id-name”
android:layout_below 位于元素的下方
android:layout_above 位于元素的的上方
android:layout_toLeftOf 位于元素的左边
android:layout_toRightOf 位于元素的右边

android:layout_alignTop 该元素的上边缘和某元素的的上边缘对齐
android:layout_alignLeft 该元素的左边缘和某元素的的左边缘对齐
android:layout_alignBottom 该元素的下边缘和某元素的的下边缘对齐
android:layout_alignRight 该元素的右边缘和某元素的的右边缘对齐

给属性赋予像素值
android:layout_marginBottom 底边缘的距离
android:layout_marginLeft 左边缘的距离
android:layout_marginRight 右边缘的距离
android:layout_marginTop 上边缘的距离

网格布局GridLayout

设置多个网格形式的空间布局,一般以从左往右,从上到下的顺序按先后顺序放置控件

GridLayout常用属性

rowCount :行

columnCount:列

设置该网格由几行几列构成

如都设置为2,则该布局为一个两行两列的网格,共可放置四个控件

Space标签的作用:挡住控件,让其不超出网格的范围

可以防止控件长宽的跨界

CATALOG
  1. 1. 布局格式
    1. 1.1. 线性布局LinearLayout
      1. 1.1.1. LinearLayout常用属性
    2. 1.2. 相对布局RelativeLayout
      1. 1.2.1. RelativeLayout常见属性
    3. 1.3. 网格布局GridLayout
      1. 1.3.1. GridLayout常用属性