Android merge

更新时间:2021-12-29

    通过merge可以消除视图层次结构的冗余;
    merge标签必须使用在根布局;
    对merge标签设置的属性是无效的。

1. 使用方式示例

1)创建一个layout,如:my_merge_layout.xml

<?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="horizontal"
    >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="button 1"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="button 2"
        />
</LinearLayout>

在这里插入图片描述

2)通过include引入上方的布局

在 activity_main.xml中通过include使用布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="this is button"
        />
    <include layout="@layout/my_merge_layout" />
</LinearLayout>

在这里插入图片描述

3)效果如下

可以看出,LinearLayout中,又嵌套了一个LinearLayout
在这里插入图片描述
(Android布局层次结构查看工具-Layout Inspector介绍:https://blog.csdn.net/cadi2011/article/details/85212762)
在这里插入图片描述

4)对my_merge_layout.xml进行修改,将LinearLayout替换为merge

这里对merge设置了属性,其实这里的属性是不会生效的!

通过include引入,系统会忽略merge并直接布局里面的两个按钮,以代替include。

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    >
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="button 1"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="button 2"
        />
</merge>

在这里插入图片描述

5)修改后效果如下

通过merge可以减少布局嵌套。
修改后,没有了多个LinearLayout嵌套了。
在这里插入图片描述
在这里插入图片描述

2. 参考文档:

Merge介绍:
    https://developer.android.google.cn/training/improving-layouts/reusing-layouts?hl=en#Merge

Android布局层次结构查看工具-Layout Inspector介绍:
    https://blog.csdn.net/cadi2011/article/details/85212762

好记性不如烂笔头!

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值