安卓开发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="按钮" />

```

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

相关推荐
非 白1 小时前
数据结构——树
数据结构·笔记·考研
小梁不秃捏2 小时前
深入浅出Java虚拟机(JVM)核心原理
java·开发语言·jvm
E___V___E4 小时前
MySQL数据库入门到大蛇尚硅谷宋红康老师笔记 高级篇 part 2
数据库·笔记·mysql
yngsqq5 小时前
c# —— StringBuilder 类
java·开发语言
星星点点洲6 小时前
【操作幂等和数据一致性】保障业务在MySQL和COS对象存储的一致
java·mysql
slomay6 小时前
项目汇报PPT转视频制作 | 有字幕和配音版
经验分享·github
xiaolingting6 小时前
JVM层面的JAVA类和实例(Klass-OOP)
java·jvm·oop·klass·instanceklass·class对象
风口上的猪20156 小时前
thingboard告警信息格式美化
java·服务器·前端
易基因科技6 小时前
易基因: ChIP-seq+DRIP-seq揭示AMPK通过调控H3K4me3沉积和R-loop形成以维持基因组稳定性和生殖细胞完整性|NAR
经验分享·数据挖掘·生物学·生物信息学
Fansv5876 小时前
深度学习-2.机械学习基础
人工智能·经验分享·python·深度学习·算法·机器学习