LinearLayout 线性布局
目录
Android LinearLayout(线性布局)简单介绍与使用示例
一、效果介绍
二、布局文件(XML)
三、Java 代码
四、程序运行效果
五、总结
在 Android 移动应用开发中,LinearLayout(线性布局) 是最常见的布局方式之一。它可以让多个控件按垂直或水平方向依次排列,通过 orientation
属性设置方向,并配合 layout_weight
实现弹性布局,非常适合构建简单、规则的界面结构。本文通过完整示例,帮助你了解并掌握 LinearLayout 的基本使用方法。
一、效果介绍
本文示例将页面分为上下两个区域,每个区域中又包含三个颜色块。
-
上半部分为水平排列的三块颜色区域
-
下半部分为垂直排列的三块颜色区域
所有区域大小按权重平均分配。
二、布局文件(XML)
文件名:res/layout/activity_main.xml
文件类型: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:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"android:orientation="vertical"><!-- 上半部分:水平排列三个颜色块 --><LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"><TextViewandroid:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="1"android:background="#F44336"/><TextViewandroid:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="1"android:background="#CDDC39"/><TextViewandroid:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="1"android:background="#00BCD4"/></LinearLayout><!-- 下半部分:垂直排列三个颜色块 --><LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:orientation="vertical"><TextViewandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:background="#9C27B0"/><TextViewandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:background="#FFC107"/><TextViewandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:background="#4CAF50"/></LinearLayout></LinearLayout>
三、Java 代码
文件名:MainActivity.java
文件类型:Java 文件
package com.example.a1;import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main); // 加载布局}
}
四、程序运行效果
运行程序后,页面被均匀分为上下两个区域:
-
上面是三个水平颜色块(红色、绿色、青色)
-
下面是三个垂直颜色块(紫色、黄色、绿色)
所有区域大小均等,界面清晰整齐,体现了 LinearLayout 的线性排列和权重分配特点。
五、总结
本文展示了 Android 中 LinearLayout 的使用方式,通过 orientation
设置方向,通过 layout_weight
控制空间分配。LinearLayout 是最基础也最常用的布局方式之一,适合构建简单、规则的 UI 界面结构。希望这个示例能帮助你更好地理解线性布局的基本用法。
如需制作复杂布局,推荐结合 RelativeLayout 或 ConstraintLayout 进一步学习使用。