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


4057

被折叠的 条评论
为什么被折叠?



