布局中<merge>、<viewstub>控件作用及实现原理

1.<include/>

<include/>标签作用重用布局

  • include标签可以使用单独的layout属性
  • include标签指定了id,同时layout也定义了id,则layout的id会被覆盖
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"   
    android:layout_width=”match_parent”  
    android:layout_height=”match_parent”  
    android:background="@color/app_bg"  
    android:gravity="center_horizontal">  
  
    <include layout="@layout/titlebar"/>  
  
    <TextView android:layout_width=”match_parent”  
              android:layout_height="wrap_content"  
              android:text="@string/hello"  
              android:padding="10dp" />  
  
    ...  
  
</LinearLayout>  

2.<merge/>

减少视图层级的复用,<merge/>标签在UI结构化优化起着非常重要的作用,可以减少多余的层级,优化UI。
使用:

  • 用于替换FrameLayout
  • 当一个布局包含另一个布局时,如一个垂直的线性布局,引入了一个垂直的include,使用merge可以消除include布局中的线性布局。
<merge xmlns:android="http://schemas.android.com/apk/res/android">  
  
    <Button  
        android:layout_width="fill_parent"   
        android:layout_height="wrap_content"  
        android:text="@string/add"/>  
  
    <Button  
        android:layout_width="fill_parent"   
        android:layout_height="wrap_content"  
        android:text="@string/delete"/>  
  
</merge>  

3.<viewstub>
需要时加载,优化初始化UI性能,如不常用的进度条、错误消息等使用viewstub,减少内存使用量,加快布局渲染。它是一个不可见,大小为0的view。

<ViewStub  
    android:id="@+id/stub_import"  
    android:inflatedId="@+id/panel_import"  
    android:layout="@layout/progress_overlay"  
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:layout_gravity="bottom" />  

使用时加载:

((ViewStub) findViewById(R.id.stub_import)).setVisibility(View.VISIBLE);  
// or  
View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate(); 

当调用inflate函数的时候,viewstub被引用的资源替代,并返回引用的view,这样程序可以直接得到view的引用而不用再次调用findViewById来查找
注:viewstub目前不支持merge标签。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 先扯两句 上次写的部分主要还是一些封装的抽象方法,这部分只是单纯的为我这种懒汉提供了便利罢了,而本次写的内容呢,则...
    半寿翁阅读 2,921评论 0 12
  • 2017.9.1 九月,从小排的爱心早餐开始! 今日初阳温热,凉风有幸,开启正能量的一个月! 早起瑜伽二十分钟,身...
    月羊不是羊阅读 249评论 0 1
  • 感赏自己今天比昨天有了很多进步,不再自怨自艾,悲天悯人!昨天我的世界仿佛是崩塌了,我痛苦无助,觉得面临的是世界末日...
    小瓶盖Q日记阅读 509评论 1 1
  • 在高中时,学习地理和历史,老师简单讲过一点,当时有了兴趣,前两天又遇到,就把它做了个简单小结,分享给大家。你们可以...
    知识分享阅读 861评论 0 1
  • 看以上这个图,学过演讲的我们都经常见过,刚开始接触演讲时,我们都知道这个等式,慢慢的我们按这个等式来练习,在几个月...
    蓝蓝桔子1126331阅读 252评论 2 2