欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 会展 > LinearLayout 线性布局

LinearLayout 线性布局

2025/4/20 20:27:30 来源:https://blog.csdn.net/2402_84971234/article/details/147353369  浏览:    关键词: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 界面结构。希望这个示例能帮助你更好地理解线性布局的基本用法。

如需制作复杂布局,推荐结合 RelativeLayoutConstraintLayout 进一步学习使用。

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词