Android Studio - 六大布局实战指南

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

1. 认识Android六大布局

刚开始学Android开发那会儿,我最头疼的就是布局了。每次打开Android Studio,面对那些LinearLayout、RelativeLayout,总是一头雾水。后来做多了项目才发现,选对布局真的能让开发效率翻倍,而且app运行起来也更流畅。

Android的六大核心布局就像是盖房子的六种不同工具:LinearLayout像积木一样直线排列,RelativeLayout像磁铁一样相对吸附,ConstraintLayout像智能拼图一样灵活,FrameLayout像相框一样层层叠加,TableLayout像表格一样整齐划分,GridLayout像网格一样精准定位。每种布局都有自己的特点和适用场景,用对了事半功倍,用错了就是各种布局嵌套和性能问题。

我记得刚开始做一个登录界面时,傻傻地用LinearLayout嵌套了五六层,结果页面加载慢不说,还经常出现布局错乱。后来改用ConstraintLayout,一个布局文件就搞定了,而且适配各种屏幕尺寸都很轻松。这就是布局选择的重要性 - 它直接影响到你的开发效率和app性能。

2. LinearLayout线性布局实战

LinearLayout是我最早接触的布局,也是最适合新手上手的布局。它的核心思想很简单:就像排队一样,要么横着排,要么竖着排。

2.1 基础属性详解

先来看一个最简单的垂直LinearLayout:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="16dp">
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="用户名"/>
        
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入用户名"/>
        
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登录"/>
</LinearLayout>

这里有几个关键属性需要特别注意:orientation决定排列方向,vertical是垂直,horizontal是水平。gravity控制子元素在布局内的对齐方式,比如center是居中,left|bottom是左下角对齐。

2.2 权重layout_weight的妙用

权重是LinearLayout最强大的功能之一,它能按比例分配剩余空间。我做过一个音乐播放器界面,进度条和音量控制就是用权重实现的:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="00:00"/>
        
    <SeekBar
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"/>
        
    <TextView
        android:layout_width="0dp"
        android:layout_height

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值