【Android】布局优化—include,merge,ViewStub的使用方法

news/2024/9/28 23:06:08/

引言

1.重要性

在Android应用开发中,布局是用户界面的基础。一个高效的布局不仅能提升用户体验,还能显著改善应用的性能。随着应用功能的复杂性增加,布局的优化变得尤为重要。优化布局能够减少渲染时间,提高响应速度,从而让用户获得更流畅的体验。

2.布局对性能的影响

布局直接影响应用的启动时间和运行时性能。嵌套过深的布局会导致测量和绘制的开销增加,进而引发界面卡顿或不流畅的问题。此外,复杂的布局会消耗更多的内存,可能导致应用崩溃。通过合理的布局设计,可以降低CPU和GPU的负担,提升整体应用的运行效率。

布局性能的基本概念

布局性能是指在Android应用中,布局系统处理视图(View)和视图组(ViewGroup)的效率。它主要涉及以下几个方面:

  1. 测量性能
    • 指计算视图大小所需的时间和资源。高效的测量可以减少布局过程中CPU的占用。
  2. 布局性能
    • 这是指在视图层级中定位和排列视图所需的时间。层级过深或过于复杂的布局会导致性能下降。
  3. 渲染性能
    • 涉及将布局绘制到屏幕上所需的时间和资源。有效的渲染能够确保界面快速响应用户操作。
  4. 内存使用
    • 低内存使用意味着更少的GC(垃圾回收),从而减少卡顿和延迟。布局性能应关注内存的合理分配和使用。

优化布局文件

使用ConstraintLayout的优势

  1. 约束系统(Constraint System)
    • ConstraintLayout 提供了一套完整的约束系统,可以通过相对定位、边距、比例、链等特性来定义子视图之间的关系。这样一来,不同视图之间可以在同一层级内相互依赖,避免了层层嵌套的问题。
  2. 灵活的相对定位
    • 使用传统布局(如LinearLayoutRelativeLayout)时,通常需要多个嵌套来满足复杂的布局需求。例如,一个水平和垂直居中的布局需要嵌套两个 LinearLayout 或者 RelativeLayout。而在 ConstraintLayout 中,只需要设置 layout_constraint 属性,即可将视图居中显示。
  3. 减少布局重绘和测量次数
    • 每增加一个层级的嵌套都会增加布局的测量和绘制时间。而 ConstraintLayout 将大部分的布局逻辑集中在一个 ConstraintLayout 中进行处理,减少了层级数量,从而提升了性能。
  4. 替代多种传统布局
    • ConstraintLayout 可以同时替代 RelativeLayoutLinearLayoutFrameLayout 等多种布局。对于一些复杂的布局需求,只需要一个 ConstraintLayout 就能完成,无需再嵌套使用其他布局容器。
  5. 链式布局(Chains)
    • ConstraintLayout 支持链式布局,可以将多个视图通过链条的形式连接在一起,根据指定的分布方式(如均匀分布、权重分布等)来排列视图。这种方式不仅减少了嵌套层级,还能更加灵活地管理视图的排列。
  6. Guideline 和 Barrier
    • ConstraintLayout 还提供了 GuidelineBarrier 等辅助控件,帮助开发者在同一层级内实现复杂的布局逻辑。例如,通过 Guideline 可以在布局中定义固定的比例参考线,方便其他视图的对齐和排列;Barrier 则可以动态地将多个视图的边界作为参考点,灵活适应视图的变化。

ConstraintLayout的使用可以参考以下博客:【Android】ConstrainLayout约束布局基本操作_android studio的constrain layout可以删除吗-CSDN博客

include使用

<include>标签可以允许在一个布局当中引入另外一个布局,那么比如说我们程序的所有界面都有一个公共的部分,这个时候最好的做法就是将这个公共的部分提取到一个独立的布局文件当中,然后在每个界面的布局文件当中来引用这个公共的布局。

下面举一个简单的例子:

我们应该都知道,目前几乎所有的软件都会有一个头布局,头布局中可以包含界面的标题、返回按钮、以及其它一些操作功能。有些软件是使用ActionBar来实现的,但是由于ActionBar的灵活性不太好,因而也有很多软件会选择自己去编写实现。因为应用中几乎所有界面都要用头布局,所以这种情况下使用<include>标签就非常合适了。

我们创建title_bar.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent" ><Buttonandroid:id="@+id/back"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_centerVertical="true"android:text="Back" /><TextViewandroid:id="@+id/title"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerInParent="true"android:text="Title"android:textSize="20sp" /><Buttonandroid:id="@+id/done"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_centerVertical="true"android:text="Done" /></RelativeLayout>

title_bar.xml中的布局非常简单,外层是一个RelativeLayout,里面只有两个Button和一个TextView,左边的Button用于实现返回功能,右边的Button用于实现完成功能,中间的TextView则可以用于显示当前界面的标题。

image-20240927175426436

在其他布局进行使用的时候直接用include就可以了:

    <include layout="@layout/title_bar" />

这样我们在修改title_bar中内容的时候就不用一个页面一个页面去修改了,直接修改文件里的就可以了。

但是我们会发现,引入title_bar后我们原本布局中的内容全不见了,原因是因为titlebar的最外层布局是一个宽高都是match_parent的RelativeLayout,它会将整个布局都填充满,因而我们原本的布局也就看不见了。我们可以将RelativeLayout的layout_height属性修改成wrap_content:

<include layout="@layout/title_bar"android:layout_width="match_parent"android:layout_height="wrap_content"/>

除了layout_height之外,我们还可以覆写titlebar中的任何一个layout属性,如layout_gravity、layout_margin等,而非layout属性则无法在<include>标签当中进行覆写。但是在覆写的时候必须要将layout_width和layout_height这两个属性也进行覆写,否则覆写效果将不会生效。

merge使用

<merge>标签是作为<include>标签的一种辅助扩展来使用的,它的主要作用是为了防止在引用布局文件时产生多余的布局嵌套。

在上面我们讲解<include>标签的用法时主要介绍了它优点,但是它也存在着一个不好的地方,就是可能会导致产生多余的布局嵌套。

新建ok_cancel_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="wrap_content"android:orientation="vertical" ><Buttonandroid:id="@+id/ok"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="20dp"android:layout_marginRight="20dp"android:text="OK" /><Buttonandroid:id="@+id/cancel"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="20dp"android:layout_marginRight="20dp"android:layout_marginTop="10dp"android:text="Cancel" /></LinearLayout>

定义了两个按钮。

当activity_main中需要输入些东西,引用上面两个按钮的时候,可以使用include引用:

    <include layout="@layout/ok_cancel_layout"/>

运行效果如下:

image-20240927194655175

但是,此时这个界面中已经存在着多余嵌套了:

在这里插入图片描述

最外层首先是一个FrameLayout

在setContentView()方法中,Android会自动在布局文件的最外层再嵌套一个FrameLayout。

具体原因可以参考博客:Android LayoutInflater原理分析,带你一步步深入了解View(一)_android layoutinflater原理分析,带你一步步深入了解view(一)-CSDN博客

然后FrameLayout中包含的是一个LinearLayout,在最外层的LinearLayout当中包含了两个元素,一个是EditText,另一个又是一个LinearLayout,然后在这个内部的LinearLayout当中才包含了确定和取消这两个按钮。

我们此时就可以用merge来优化布局。修改ok_cancel_layout.xml中的代码:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"><Buttonandroid:id="@+id/ok"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="20dp"android:layout_marginRight="20dp"android:text="OK" /><Buttonandroid:id="@+id/cancel"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="20dp"android:layout_marginRight="20dp"android:layout_marginTop="10dp"android:text="Cancel" /></merge>

这里我们将ok_cancel_layout最外层的LinearLayout布局删除掉,换用了<merge>标签,这就表示当有任何一个地方去include这个布局时,会将<merge>标签内包含的内容直接填充到include的位置,不会添加任何额外的布局结构。

当前的View结构就变成了:

在这里插入图片描述

现在EditText和两个按钮都直接包含在了LinearLayout下面,去掉了多余的嵌套。

ViewStub使用

有的时候我们会遇到这样的场景,就是某个布局当中的元素非常多,但并不是所有元素都一起显示出来的,而是普通情况下只显示部分常用的元素,而那些不常用的元素只有在用户进行特定操作的情况下才会显示出来。

虽然设置其它元素可见不可见也可以实现该操作,但是相应的元素还是会进行加载。那么我们如何才能让这些不常用的元素仅在需要时才去加载呢?Android为此提供了一种非常轻量级的控件,ViewStub。ViewStub虽说也是View的一种,但是它没有大小,没有绘制功能,也不参与布局,资源消耗非常低,将它放置在布局当中基本可以认为是完全不会影响性能的。

我们新建profile_extra.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="vertical" ><EditTextandroid:id="@+id/edit_extra1"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="20dp"android:layout_marginRight="20dp"android:hint="Extra field 1" /><EditTextandroid:id="@+id/edit_extra2"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="20dp"android:layout_marginRight="20dp"android:layout_marginTop="10dp"android:hint="Extra field 2" /><EditTextandroid:id="@+id/edit_extra3"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="20dp"android:layout_marginRight="20dp"android:layout_marginTop="10dp"android:hint="Extra field 3" /></LinearLayout>

现在定义了三个EditText当作不常用控件。

修改activity_main.xml:

<?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:id="@+id/main"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><include layout="@layout/title_bar"android:layout_width="match_parent"android:layout_height="wrap_content"/><EditTextandroid:id="@+id/edit"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginBottom="10dp"android:layout_marginLeft="20dp"android:layout_marginRight="20dp"android:layout_marginTop="10dp"android:hint="Edit something here" /><Buttonandroid:id="@+id/more"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="right"android:layout_marginRight="20dp"android:layout_marginBottom="10dp"android:text="More" /><ViewStubandroid:id="@+id/view_stub"android:layout="@layout/profile_extra"android:layout_width="match_parent"android:layout_height="wrap_content"/><include layout="@layout/ok_cancel_layout"/></LinearLayout>

我们新增了一个More Button用来加载不常用元素,后在Button的下面定义了一个ViewStub。通过layout属性将profile_extra布局传入进来,。

下来在MainActivity里添加点击事件:

public class MainActivity extends AppCompatActivity {private EditText editExtra1;private EditText editExtra2;private EditText editExtra3;private Button moreButton;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);return insets;});moreButton = (Button) findViewById(R.id.more);moreButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {ViewStub viewStub = (ViewStub) findViewById(R.id.view_stub);if (viewStub != null) {View inflatedView = viewStub.inflate();editExtra1 = (EditText) inflatedView.findViewById(R.id.edit_extra1);editExtra2 = (EditText) inflatedView.findViewById(R.id.edit_extra2);editExtra3 = (EditText) inflatedView.findViewById(R.id.edit_extra3);}}});}
}

当点击More Button之后我们首先会调用findViewById()方法将ViewStub的实例获取到,调用inflate()方法或者setVisibility(View.VISIBLE)都可以将隐藏的布局给加载出来,而加载的这个布局就是刚才在XML当中配置的profile_extra布局。

效果如下:

点击前:

image-20240927204637008

点击后:

image-20240927204701979

小结

本篇博客主要分享了对于布局的优化方面的知识,并讲解了include,merge,ViewStub的使用方法,希望对大家有所帮助。

参考:Android最佳性能实践(四)——布局优化技巧_android 在代码里生成布局性能-CSDN博客


已经到底啦!!


http://www.ppmy.cn/news/1531375.html

相关文章

MySQL(面试问题)

MySQL用了什么索引结构 B 树 B树的优势 对比B树&#xff0c;B树的数据放在叶子节点&#xff0c;非叶子节点存放索引&#xff0c;而B树中&#xff0c;行数据放在非叶子节点中。相比之下&#xff0c;B一次读入的索引节点更多&#xff0c;减少IO次数&#xff0c;缩短查询时间。 对…

浙大数据结构:05-树9 Huffman Codes

这道题难度挺大&#xff0c;写起来较为费劲&#xff0c;这里我依然使用了STL库&#xff0c;使得代码量大幅减少不过百行&#xff0c;便于大家理解。 机翻&#xff1a; 1、条件准备 数组存储字符对应频率&#xff0c;n,student存储输入多少字符&#xff0c;有多少学生测试。 …

集群系统架构

ShedLock 是一个用于分布式环境下的锁机制&#xff0c;确保在同一时间点只有一个节点能够执行特定的定时任务。其核心原理是通过公共存储&#xff08;如数据库、Redis 等&#xff09;来实现锁的管理12。 具体来说&#xff0c;当一个任务在某个节点上开始执行时&#xff0c;该节…

node-red-L3-重启指定端口的 node-red

重启指定端口 目的步骤查找正在运行的Node.js服务的进程ID&#xff08;PID&#xff09;&#xff1a;停止Node.js服务&#xff1a;启动Node.js服务&#xff1a; 目的 重启指定端口的 node-red 步骤 在Linux系统中&#xff0c;如果你想要重启一个正在运行的Node.js服务&#x…

cubemx配置ADC

参考博客&#xff1a;https://blog.csdn.net/qq_29031103/article/details/119894077 生成代码&#xff1b; 接着编写代码&#xff1a; 1&#xff09;在main函数bsp初始化部分&#xff1b; 添加&#xff1a;HAL_ADCEx_Calibration_Start(&hadc1); 2&#xff09;在…

《The Graceful Dance of Fog》

《The Graceful Dance of Fog》 Fog, like an ethereal white silk, quietly blankets the expanse of heaven and earth. It resembles a mysterious dancer, moving in silence and enshrouding the whole world in its dreamlike embrace. "The fog entwines aroun…

【CSS】背景

background-color 颜色background-image 图像background-size 缩放background-repeat 平铺background-position 定位background-clip 裁剪区域background-origin 开始区域background-attachment 滚动方式 background-color 颜色 <style>div{width: 200px;height: 100px;…

react通过下拉框选择多个,并展示在下方的方式

以备后用&#xff0c;直接上代码&#xff1a; 一、方法&#xff1a; //查询学校一级部门列表async orgFirstLevelList() {let data {schoolId:this.state.schoolId};let depList await orgFirstLevelList(data);this.setState({depList: depList})}//删除所选部门deleteDep…