安卓入门系列-04常见布局之LinearLayout(线性布局)

尽管现在有了很多第三方封装的更加合适的布局定义。(各个地区随着人们的接受程度各不相同)但是作为官方提供的最先的几大布局,学习一下是必要的,因为很多布局都是在这些的基础上开发出来的。

最基础的有六大布局,分别为LinearLayout(线性布局)、TableLayout(表格布局)、FrameLayout(帧布局)、RelativeLayout(相对布局)、GridLayout(网格布局)以及AbsoluteLayout(绝对布局)。

首先接触的是开发中最常用的布局之一---线性布局(linearlayout)。

1.什么是线性布局

线性布局由 LinearLayout 类实现, 它可以控制各组件横向或纵向排列。简单来说是向一个方向不断排列组件的布局。

2.常见属性

android:orientation

这是最核心的属性,控制组件的排列方向,只有两个值 horizon(水平排列)和vertical(垂直排列)。

简单测试一下。(添加了三个按钮)

<?xml version="1.0" encoding="utf-8"?>
<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="com.zc.helloworld.MainActivity"
    android:orientation="vertical"
    >

    <Button
        android:id="@+id/btn_01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I am Button"/>
    <Button
        android:id="@+id/btn_02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I am Button"/>
    <Button
        android:id="@+id/btn_03"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I am Button"/>


</LinearLayout>

两种效果如下。

android:gravity 

设置组件的对齐方式,影响范围是该布局内部的每一个组件。属性值可设为 top(顶部对齐) 、bottom(底部对齐) 、left(左对齐) 、right(右对齐) 、center_vertical(垂直方向居中) 、 fill_vertical(垂直方向填充) 、 center_horizontal(水平方向居中) 、 fill_horizontal(水平方向填充) 、center(垂直与水平方向都居中) 、 fill (填充)、  clip_vertical(垂直方向裁剪) 、  clip_horizontal(水平方向裁剪) 。

可以多个属性串联用"|"隔开。

在上面代码排列方向后添加一行。

android:gravity="center"

效果如下。

android:baselineAligned            

该属性设为 false ,该布局管与它的子元素的基线对其会失效。

android:divider

设置垂直布局时两个按钮直接的分隔条。

android:measureWithLargestChild 

该属性设为 true 时,所有带权重的子元素都会具有最大子元素的最小尺寸。

3.子元素属性

android:layout_gravity    

指定该子元素在 LinearLayout 中的对其方式。

android:layout_weight    

指定该子元素在 LinearLayout 中所占的权重。

猜你喜欢

转载自blog.csdn.net/zhouchen1998/article/details/82924745