[android]笔记4-线性布局

Android的布局管理器本身就是一个UI组件,所有的布局管理器都是ViewGroup的子类。图2.7显示了Android布局管理器的类图。

这里写图片描述


图2.7 Android布局管理器的类图

从图2.7可以看出,所有布局都可作为容器类使用,因此可以调用多个重载的addView()向布局管理器中添加组件。实际上,我们完全可以用一个布局管理器嵌套到其他布局管理器中——因为布局管理器也继承了View,也可以作为普通UI组件使用。
线性布局
线性布局由LinearLayout类来代表,它会将容器里的组件一个挨着一个地排列起来。LinearLayout可以控制各组件横向排列(通过设置android:orientation属性控制),也可控制各组件横向排列。

Android的线性布局不会换行,当组件一个挨着一个地排列到头之后,剩下的组件将不会被显示出来。
例如定义如下XML布局管理器:

<?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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="right|center_horizontal">
    <Button
    android:id="@+id/bn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/bn1"/>
    <Button
        android:id="@+id/bn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/bn2"/>
    <Button
        android:id="@+id/bn3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/bn3"/>
    <Button
        android:id="@+id/bn4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/bn4"/>
    <Button
        android:id="@+id/bn5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/bn5"/>
</LinearLayout>

上面的界面布局非常简单,它只是定义了一个简单的线性布局,并在线性布局中定义了5个按钮。定义线性布局时使用粗体字代码指定了垂直排列所有组件,而且所有组件对齐到容器底部并且水平居中,运行上面的程序,使用Activity显示上面的界面布局,将看到如图2.8所示界面

这里写图片描述


图2.8 垂直的线性布局,底部、居中对齐

如果将上面的布局文件中android:gravity=”bottom|center_horizontal”改为android:gravity=”right|center_vertical”——也就是所有组件水平右对齐、垂直居中,再次使用Activity显示该界面布局将看到如图2.9所示界面。

这里写图片描述


图2.9垂直的线性布局,水平居中、垂直居中对齐

如果我们将上面的线性布局的方向改为水平,也就是设置android:orientation=”horizontal”,并设置gravity=”top”,再次使用Activity来显示该界面布局将看到如图2.10所示界面

这里写图片描述


图2.10水平的线性布局,顶端对齐

从图2.10所示的运行结果可以看出,当采用线性布局来管理5个按钮组件时,由于这5个按钮组件无法在一行中同时显示出来,但LinearLayout不会换行显示多余的组件,因此图2.10中看不到第5个按钮。

相关文章

AdvserView.java package com.earen.viewflipper; import an...
ImageView的scaleType的属性有好几种,分别是matrix(默认)...
文章浏览阅读8.8k次,点赞9次,收藏20次。本文操作环境:win1...
文章浏览阅读1.2w次,点赞15次,收藏69次。实现目的:由main...
文章浏览阅读3.8w次。前言:最近在找Android上的全局代理软件...
文章浏览阅读2.5w次,点赞17次,收藏6次。创建项目后,运行项...