RelativeLayout与LinearLayout的区别
首先 ,简单介绍一下两位主角:
LinearLayout(线性布局):最常用的布局
这种布局在显示组件的时候会默认保持组件之间的间隔以及组件之间的互相对齐。线性布局显示组件的方式有两种方式:垂直和水平,是通过orientation来设定的。
RelativeLayout(相对布局): 第二常用的布局
它相对于线性布局来说比较灵活,在进行组件布局的时候用线性布局往往需要进行布局嵌套,而相对布局就不会那么麻烦,每个组件都可以指定与其它组件或父组件的位置。
另外三位布局顺便说一下:TableLayout(表格布局)、AbsoluteLayout(绝对布局)、FrameLayout(单帧布局)
本文主要通过一个很简单的例子,看看两者的区别:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="@drawable/selector_btn_bar"
android:paddingLeft="15dp"
android:paddingRight="15dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="这个靠左"
android:textSize="16sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="这个靠右"
android:textSize="16sp" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="@drawable/selector_btn_bar"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:layout_weight="15"
android:text="这个靠左"
android:textSize="16sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:text="这个靠右"
android:textSize="16sp"
/>
</LinearLayout>
</LinearLayout>
运行以上代码,选择一个虚拟机(Nexus 5)展示如下:
第一行是用相对布局实现,第二行是用线性布局实现,之所以能达到一样的效果是对线性布局中的两个TextView进行了比例调整。
如果换一个机型的话(Nexus 5)可能就会有变化了:
所以在这种情况下,线性布局明显不如相对布局好用,线性布局还是太死板了,还记得开头那句话吗:“在进行组件布局的时候用线性布局往往需要进行布局嵌套,而相对布局就不会那么麻烦”。就是这个意思。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步