Android性能优化xml之<include>、<merge>、<ViewStub>标签的使用

一、使用<include>标签对“重复代码”进行复用

          <include>标签是我们进行Android开发中经常用到的标签,比如多个界面都同样用到了一个左侧筛选功能的布局,这个筛选界面可以使用一个单独的xml,然后使用时用<include>引用。

二、使用<merge>标签删除多余的层级

           <merge>标签多用于替换FrameLayout或者当一个布局包含另外一个布局时,<merge>标签用于消除父子层次结构中多余的视图组。例如:我们建立的一个布局是垂直的,此时如果引入另外一个垂直布局的<include>,这时如果include布局使用的LinearLayout就没意义了,使用的话反而会减慢UI表现。这时我们可以使用<merge>标签,它可以排除一个布局插入另外一个布局时产生的多余的ViewGroup。具体用法如下

1.用法1替换FrameLayout

 

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="我是button" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="我又是个button" />

</merge>

 

 

 

2.用法2插入布局时消除多余的视图组

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

</LinearLayout>

 

其中fragment_main是用法1中的布局,这时我们能看到按钮是垂直排列的。

         <merge>只能作为xml布局的根标签使用,当Inflate以<merge>开头的布局文件时,必须指定一个父ViewGroup并且必须设定attachToBoot为true。

 

三、使用<ViewStub>标签进行“延迟加载”

         <ViewStub>标签最大的特点就是你需要的时候才会加载,并且不会影响UI初始化的性能。一些不常用的布局文件如显示错误信息的diaolog,这时都可以用<ViewStub>标签进行优化。

          有人也许会说,我用View.GONE也可以达到相同的效果呀?那么两者有什么区别呢?

          <VewStub>只能inflate一次,用完以后<ViewStub>就会置空,后期不能再次使用,只有重新开启应用或者杀死进程后才可再次使用。类似显示隐藏按钮这种功能是不能实现的。View.GONE比较费资源,虽然已经GONE掉了,但显示View时还是会加载的。

 

xml中使用方法如下

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <Button
        android:onClick="click"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="我的按钮"/>

   <ViewStub
    android:id="@+id/vs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout="@layout/layout_button"/>

</LinearLayout>

activity中加载

public void click(View view) {
    ViewStub vs = (ViewStub) findViewById(R.id.vs);
    vs.inflate();
}

< ViewStub>可完全取代< include>,但< ViewStub>目前还无法取代< merge>  

 

      

 

posted @ 2017-09-25 17:55  wangchuan886  阅读(976)  评论(0编辑  收藏  举报