Android零基础入门第25节:简单且最常用的LinearLayout线性布局

本文详细介绍了Android中常用的LinearLayout布局,包括其方向设置、填充模型和权重分配。LinearLayout有两种形式:水平和垂直布局,通过android:orientation属性切换。权重用于在布局中按比例分配空间,使组件能平均占据屏幕宽度。同时,讲解了如何使用android:layout_width和android:layout_height属性控制组件尺寸,并强调layout_weight属性只能在LinearLayout的直接子元素中使用。
摘要由CSDN通过智能技术生成

良好的布局设计对于UI界面至关重要,在前面也简单介绍过,目前Android中的布局主要有6种,创建的布局文件默认为RelativeLayout相对布局,而在前面的示例学习中,我们只是简单利用了一下LinearLayout线性布局,那么接下来分别对其进行详细学习。

一、认识LinearLayout

线性布局是Android中较为常用的布局方式,使用LinearLayout标签。线性布局主要有两种形式,一种是水平线性布局,一种是垂直线性布局。需要注意的是Android的线性布局不会换行,当组件一个挨着一个地排列到头之后,剩下的组件将不会被显示出来。

下表显示了LinearLayout支持的常用XML属性及相关方法的说明。

LinearLayout 包含的所有子元素都受 LinearLayout.LayoutParams 控制,因此 LinearLayout包含的子元素可以额外指定如如下属性。

  • android:layout_gravity:指定该子元素在LinearLayout中的对齐方式。

  • android:layout_weight:指定该子元素在LinearLayout中所占的权重。

二、LinearLayout详解

 接下来分别从方向、填充模型、权重、对齐、内边距、外边距几个方面来进一步学习LinearLayout 的使用,当然其中一部分也适用于后续布局文件。

1、方向

通过“android:orientation”属性设置线性布局的方向,将值设置为horizontal表示行,设置为vertical表示列,默认为horizontal。

接下来通过一个简单的示例程序来学习LinearLayout 的使用用法。

同样使用WidgetSample工程,继续使用app/main/res/layout/目录下的activity_main.xml文件,在其中填充如下代码片段:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="按钮一"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="按钮二"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="按钮三"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="按钮四"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="按钮五"/>
</LinearLayout>

运行程序,可以看到下图左侧所示界面效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值