安卓开发LinearLayout的属性极其用法

线性布局(LinearLayout)是 Android 开发中常用的布局之一,它可以按照水平(horizontal)或垂直(vertical)方向排列子视图。以下是线性布局的一些常用属性和用法:

  1. **android:orientation**:指定布局方向,可以设置为"horizontal"(水平)或"vertical"(垂直)。

示例:

```xml

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="vertical">

<!-- 垂直布局 -->

</LinearLayout>

```

  1. **android:layout_weight**:设置子视图在布局中的相对权重,用于控制子视图在分配额外空间时的相对大小比例。通常与布局的宽度或高度为 "0dp" 配合使用。

示例:

```xml

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="horizontal">

<Button

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="按钮1" />

<Button

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="2"

android:text="按钮2" />

</LinearLayout>

```

  1. **android:gravity**:设置布局中子视图的对齐方式,例如居中、靠左、靠右等。注意,该属性影响的是子视图在布局内的对齐方式,而不是布局本身。

示例:

```xml

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="vertical"

android:gravity="center_horizontal">

<!-- 子视图会在垂直方向上居中对齐 -->

</LinearLayout>

```

  1. **android:layout_gravity**:设置布局在父布局中的对齐方式,例如居中、靠左、靠右等。

示例:

```xml

<LinearLayout

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_gravity="center_horizontal">

<!-- 布局会在水平方向上居中对齐 -->

</LinearLayout>

```

  1. **android:layout_margin** 和 **android:layout_marginStart**、**android:layout_marginEnd**、**android:layout_marginTop**、**android:layout_marginBottom**:设置子视图与父布局或其他子视图之间的外边距。

示例:

```xml

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_margin="8dp"

android:text="按钮" />

```

这些是线性布局中常用的一些属性和用法。

相关推荐
吴声子夜歌23 分钟前
Guava——散列
java·guava
用户31268748772024 分钟前
AQS 到底怎么排队的?CLH 队列、state 与条件变量全链路拆解
java
Json____30 分钟前
springboot开发高校选课管理系统:从零构建前后端分离的全栈实践
java·spring boot·后端·毕业设计·毕设·wwwoop.com
xcl092540 分钟前
民宿预约系统开发实战:从需求分析到上线部署全流程解析
java·spring boot
步行cgn1 小时前
为何以继承方式引入SpringBoot
java·spring boot·后端
CoderYanger1 小时前
A.每日一题:1140. 石子游戏 II
java·程序人生·算法·leetcode·游戏·职场和发展·深度优先
禾高网络1 小时前
养老系统开发:背景、架构与养老行业展望
java·大数据·人工智能·小程序·架构
杉氧1 小时前
打破边界(一):实战编写 Android/iOS 原生模块 (Native Modules)
android·react native·前端框架
CCYe、1 小时前
新模型上线、旧模型下线:企业AI网关如何管住模型版本
java·网络·数据库·人工智能