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)可能就会有变化了:


所以在这种情况下,线性布局明显不如相对布局好用,线性布局还是太死板了,还记得开头那句话吗:“在进行组件布局的时候用线性布局往往需要进行布局嵌套,而相对布局就不会那么麻烦”。就是这个意思。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端开发黑子Kuroko

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值