安卓开发教程09:线性布局LinearLayout

105 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第9天,点击查看活动详情

今天我们来说的是Android 中的布局,Android中有六大布局,而我们今天来说的是第一种布局,线性布局。

LinearLayout线性布局

线性布局顾名思义就是直线方式的布局,要么垂直布局要么水平布局。

我们来写一下试试看效果: 要线性布局,首先要把布局的节点定义为LinearLayout。然后我们的定义三个TextView用于显示内容文本(并且把前后两个的背景色设为黑色,文字颜色设置为白色,以便于区分他们之间,再把宽度设置为20dp。)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="20dp"
        android:layout_height="wrap_content"
        android:text="@string/linearText"
        android:background="@color/black"
        android:textColor="@color/white"/>

    <TextView
        android:layout_width="20dp"
        android:layout_height="wrap_content"
        android:text="@string/linearText"/>

    <TextView
        android:layout_width="20dp"
        android:layout_height="wrap_content"
        android:text="@string/linearText"
        android:background="@color/black"
        android:textColor="@color/white"/>

</LinearLayout>

image.png

如图所示,我们定义的三个20dp宽的TextView,按照水平方向一次排开。这是默认的线性布局的排列方式,如果我们把TextView的宽度设置为match_parent,那么只会显示第一个TextView,因为LinearLout只会按照一个放向排列,要么水平要么吹制,超出的部分不会折行显示。

下面我们来看下怎么让它垂直显示:

  1. 我们先把TextView 的宽度设置为 mach_parent
  2. 给LinearLayout 添加 orientation 属性 并设置为 vertical

image.png

我们看到效果如我们预想的一样变成了垂直布局方式。

weight属性:

如果我们想要让这三个TextView 水平排列并且按照1:2:1 的方式去排列。 那么我们只需要:

  1. 把LinearLayout 的 orientation 设置为 horizontal
  2. TextView 的宽度设置为 0dp
  3. 给TetxView 添加 属性 Layout_weight 并按照1:2:1 的比例设置对于的值

效果如下

image.png

那么 Android 的线性布局就介绍到这里,其实相对来说还是比较简单的,但是大家得在实际使用中需要灵活搭配其他的布局一起使用起来才能足以应对各种场景。