Android布局性能优化

Reading time ~1 minute

前言

  • 我们每天都在写各种各样的布局,对于一些简单的布局我们不会考虑性能的问题,但是对于一些复杂且层级嵌套较深的布局有没有想过可能存在的性能问题呢?接下来介绍几个Layout标签轻松优化布局性能

1.Include标签

介绍:

  • include标签的作用就是把一些复杂或者可重用的的页面抽取出来单独放到一个xml文件中,然后使用此标签导入到需要使用的布局中

用法:

<include
android:id="@+id/include"
layout="@layout/引用的布局文件" />

注意:

  • include标签若指定了ID属性,而你的layout也定义了ID,则你的layout的ID会被覆盖
  • include标签中所有的Android:layout_*都是有效的,前提是必须要写layout_width和layout_height两个属性。

2.Merge标签

介绍:

  • merge标签的作用是合并UI布局,减少视图层级,多用于替换FrameLayout(Activity`的根布局为`FrameLayout)或者当一个布局包含另一个布局时(布局的根元素必须一致)

用法:

  • 因为Activity的根元素是FrameLayout,如果你以前这样写Activity的布局文件:
< FrameLayout   xmlns:android = "http://schemas.android.com/apk/res/android"
     android:layout_width = "fill_parent"
     android:layout_height = "fill_parent" >
     < ImageView
         android:layout_width = "fill_parent"
         android:layout_height = "fill_parent"  
         android:scaleType = "center"
         android:src = "@drawable/sample"   />
     < TextView
         android:layout_width = "wrap_content"
         android:layout_height = "wrap_content"
         android:text = "sample"   />
</ FrameLayout >
  • 现在你可以把根元素FrameLayout换成merge,像这样:
< merge   xmlns:android = "http://schemas.android.com/apk/res/android" >
     < ImageView
         android:layout_width = "fill_parent"
         android:layout_height = "fill_parent"  
         android:scaleType = "center"
         android:src = "@drawable/sample"   />
     < TextView
         android:layout_width = "wrap_content"
         android:layout_height = "wrap_content"
         android:text = "sample"   />
</ merge >
  • 这时通过HierarchyViewer工具,你可以看到FrameLayout已经不见了

注意:

  • include进来的布局文件可以使用merge标签

  • 使用merge作为布局的根元素的时候,我们原来被merge替代的顶节点是不能有多余的属性的,否则merge实现不了.
  • merge只能用于xml layout文件的根元素
  • 在代码中inflate一个以merge为根元素的 布局文件时候,你需要指定一个ViewGroup作为其容器,并且要设置attachToRoottrue

3.ViewStub

介绍:

  • ViewStub是一个用于在运行时加载布局资源、不可见、宽高为0的View(未inflate时,隐藏、不绘制、宽高为0,不会消耗程序资源)
  • 多用于在程序运行时根据条件来决定显示/隐藏哪个视图

用法:

  • xml使用ViewStub占位
<ViewStub 
	android:layout="@layout/text" 
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:id="@+id/viewStub" />
  • 在需要时inflate
//方法1
ViewStub stub = (ViewStub)findViewById(R.id.viewStub);
stub.inflate(); //显示布局
//方法2
ViewStub stub = (ViewStub)findViewById(R.id.viewStub);
stub.setVisibility(View.VISIBLE);

注意:

  • 当调用inflate()函数的时候,ViewStub被引用的资源替代,并且返回引用的view,这样程序可以直接得到引用的view而不用再次调用函数findViewById()来查找了。

  • ViewStub只能够被inflate一次,一旦加载后ViewStub对象就会被置为空;
  • ViewStub目前不支持merge

4.Space

介绍:

  • Space用于在布局文件中占位(如分割线),不绘制(未实现onDraw方法),但是有宽高,用于解决过渡绘制

用法:

 <Space
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

注意:

  • Space只能设置宽高,因为他没有重写onDraw方法,所有就算设置了android:background也是无效的

为什么进步太慢,因为你没有一个好习惯

有人问我如何做好架构设计?怎样灵活运用设计模式?我的回答是,你做不好这些只是因为你没有养成一个良好的编程习惯我为什么写这么多开源框架,还长期保持维护?除了我想让更多人受益于开源外,还有一点就是,我想保持我良好的编程习惯写业务代码也可以保持良好的编程习惯啊能,但是太慢!## ...… Continue reading