Android使用ViewStub提高布局性能

移动开发 Android
在Android开发中,View是我们必须要接触的用来展示的技术.通常情况下随着View视图的越来越复杂,整体布局的性能也会随之下降.这里介绍一个在某些场景下提升布局性能的View,它就是ViewStub.

[[171874]]

在Android开发中,View是我们必须要接触的用来展示的技术.通常情况下随着View视图的越来越复杂,整体布局的性能也会随之下降.这里介绍一个在某些场景下提升布局性能的View,它就是ViewStub.

ViewStub是什么

  • ViewStub是View的子类
  • 它不可见,大小为0
  • 用来延迟加载布局资源

注,关于Stub的解释

A stub is a small program routine that substitutes for a longer program, possibly to be loaded later or that is located remotely

在Java中,桩是指用来代替关联代码或者未实现代码的代码.

ViewStub使用场景

如上图所示,

  • 一个ListView包含了诸如 新闻,商业,科技 等Item
  • 每个Item又包含了各自对应的子话题,
  • 但是子话题的View(蓝色区域)只有在点击展开按钮才真正需要加载.
  • 如果默认加载子话题的View,则会造成内存的占用和CPU的消耗

所以,这时候就ViewStub就派上用处了.使用ViewStub可以延迟加载布局资源.

ViewStub 怎么用

1.在布局文件中使用ViewStub标签

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <RelativeLayout 
  3.         xmlns:android="http://schemas.android.com/apk/res/android" 
  4.         xmlns:tools="http://schemas.android.com/tools" 
  5.         android:layout_width="match_parent" 
  6.         android:layout_height="match_parent" 
  7.         android:paddingLeft="@dimen/activity_horizontal_margin" 
  8.         android:paddingRight="@dimen/activity_horizontal_margin" 
  9.         android:paddingTop="@dimen/activity_vertical_margin" 
  10.         android:paddingBottom="@dimen/activity_vertical_margin" 
  11.         tools:context="com.droidyue.viewstubsample.MainActivity"> 
  12.  
  13.     <Button 
  14.             android:id="@+id/clickMe" 
  15.             android:text="Hello World!" 
  16.             android:layout_width="wrap_content" 
  17.             android:layout_height="wrap_content"/> 
  18.      
  19.     <ViewStub 
  20.             android:id="@+id/myViewStub" 
  21.             android:inflatedId="@+id/myInflatedViewId" 
  22.             android:layout="@layout/include_merge" 
  23.             android:layout_width="wrap_content" 
  24.             android:layout_height="wrap_content" 
  25.             android:layout_below="@id/clickMe" 
  26.     /> 
  27. </RelativeLayout> 

2.在代码中inflate布局

  1. ViewStub myViewStub = (ViewStub)findViewById(R.id.myViewStub); 
  2. if (myViewStub != null) { 
  3.     myViewStub.inflate(); 
  4.     //或者是下面的形式加载 
  5.     //myViewStub.setVisibility(View.VISIBLE); 

关于ViewStub的事

  • 除了 inflate 方法外,我们还可以调用 setVisibility() 方法加载布局文件
  • 一旦加载布局完成后,ViewStub会从当前布局层级中删除
  • android:id 指定ViewStub ID,用于查找ViewStub进行延迟加载
  • android:layout 延迟加载布局的资源id
  • android:inflatedId 加载的布局被重写的id,这里为RelativeLayout的id

ViewStub的不足

官方的文档中有这样一段描述

Note: One drawback of ViewStub is that it doesn’t currently support the tag in the layouts to be inflated.

意思是ViewStub不支持 标签.

关于不支持 标签的程度,我们进行一个简单的验证

验证一:直接 标签

如下,我们有布局文件名为merge_layout.xml

  1. <merge xmlns:android="http://schemas.android.com/apk/res/android"> 
  2.  
  3.     <Button            android:layout_width="fill_parent" 
  4.             android:layout_height="wrap_content" 
  5.             android:text="Yes"/> 
  6.  
  7.     <Button            android:layout_width="fill_parent" 
  8.             android:layout_height="wrap_content" 
  9.             android:text="No"/> 
  10.  
  11. </merge> 

 

替换对应的ViewStub的android:layout属性值之后,运行后(点击Button按钮)得到产生了如下的崩溃

  1. E AndroidRuntime: android.view.InflateException: Binary XML file line #1: <merge /> can be used only with a valid ViewGroup root and attachToRoot=true 
  2. E AndroidRuntime:         at android.view.LayoutInflater.inflate(LayoutInflater.java:551) 
  3. E AndroidRuntime:         at android.view.LayoutInflater.inflate(LayoutInflater.java:429) 
  4. E AndroidRuntime:         at android.view.ViewStub.inflate(ViewStub.java:259) 
  5. E AndroidRuntime:         at com.droidyue.viewstubsample.MainActivity$1.onClick(MainActivity.java:20) 
  6. E AndroidRuntime:         at android.view.View.performClick(View.java:5697) 
  7. E AndroidRuntime:         at android.widget.TextView.performClick(TextView.java:10815) 
  8. E AndroidRuntime:         at android.view.View$PerformClick.run(View.java:22526) 
  9. E AndroidRuntime:         at android.os.Handler.handleCallback(Handler.java:739) 
  10. E AndroidRuntime:         at android.os.Handler.dispatchMessage(Handler.java:95) 
  11. E AndroidRuntime:         at android.os.Looper.loop(Looper.java:158) 
  12. E AndroidRuntime:         at android.app.ActivityThread.main(ActivityThread.java:7237) 
  13. E AndroidRuntime:         at java.lang.reflect.Method.invoke(Native Method) 
  14. E AndroidRuntime:         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
  15. E AndroidRuntime:         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
  16. E AndroidRuntime: Caused by: android.view.InflateException: <merge /> can be used only with a valid ViewGroup root and attachToRoot=true 
  17. E AndroidRuntime:         at android.view.LayoutInflater.inflate(LayoutInflater.java:491) 
  18. E AndroidRuntime:         ... 13 more 

可见,直接的 标签,ViewStub是不支持的.

验证二 间接的ViewStub

下面布局间接使用了merge标签.文件名为 include_merge.xml

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  3.               android:orientation="vertical" 
  4.               android:layout_width="match_parent" 
  5.               android:layout_height="match_parent"> 
  6.         <include layout="@layout/merge_layout"/> 
  7. </LinearLayout> 

 

然后修改ViewStub的 android:layout 值,运行,一切正常.

除此之外,本例也验证了ViewStub也是对 标签支持良好的.

关于ViewStub的一点代码剖析

inflate vs setVisibility

inflate和setVisibility的共同点是都可以实现加载布局

  1. /**     * When visibility is set to {@link #VISIBLE} or {@link #INVISIBLE}, 
  2.      * {@link #inflate()} is invoked and this StubbedView is replaced in its parent 
  3.      * by the inflated layout resource. 
  4.      * 
  5.      * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 
  6.      * 
  7.      * @see #inflate()  
  8.      */ 
  9.     @Override 
  10.     public void setVisibility(int visibility) { 
  11.         if (mInflatedViewRef != null) { 
  12.             View view = mInflatedViewRef.get(); 
  13.             if (view != null) { 
  14.                 view.setVisibility(visibility); 
  15.             } else { 
  16.                 throw new IllegalStateException("setVisibility called on un-referenced view"); 
  17.             } 
  18.         } else { 
  19.             super.setVisibility(visibility); 
  20.             if (visibility == VISIBLE || visibility == INVISIBLE) { 
  21.                 inflate(); 
  22.             } 
  23.         } 
  24.     } 

setVisibility只是在ViewStub***次延迟初始化时,并且visibility是非 GONE 时,调用了 inflate 方法.

inflate源码

通过阅读下面的inflate方法实现,我们将更加理解

  • android:inflatedId的用途
  • ViewStub在初始化后从视图层级中移除
  • ViewStub的layoutParameters应用
  • mInflatedViewRef通过弱引用形式,建立ViewStub与加载的View的联系.

 

  1. /**     * Inflates the layout resource identified by {@link #getLayoutResource()} 
  2.      * and replaces this StubbedView in its parent by the inflated layout resource. 
  3.      * 
  4.      * @return The inflated layout resource. 
  5.      * 
  6.      */ 
  7.     public View inflate() { 
  8.         final ViewParent viewParent = getParent(); 
  9.  
  10.         if (viewParent != null && viewParent instanceof ViewGroup) { 
  11.             if (mLayoutResource != 0) { 
  12.                 final ViewGroup parent = (ViewGroup) viewParent; 
  13.                 final LayoutInflater factory = LayoutInflater.from(mContext); 
  14.                 final View view = factory.inflate(mLayoutResource, parent, 
  15.                         false); 
  16.  
  17.                 if (mInflatedId != NO_ID) { 
  18.                     view.setId(mInflatedId); 
  19.                 } 
  20.  
  21.                 final int index = parent.indexOfChild(this); 
  22.                 parent.removeViewInLayout(this); 
  23.  
  24.                 final ViewGroup.LayoutParams layoutParams = getLayoutParams(); 
  25.                 if (layoutParams != null) { 
  26.                     parent.addView(view, index, layoutParams); 
  27.                 } else { 
  28.                     parent.addView(view, index); 
  29.                 } 
  30.  
  31.                 mInflatedViewRef = new WeakReference<View>(view); 
  32.  
  33.                 if (mInflateListener != null) { 
  34.                     mInflateListener.onInflate(this, view); 
  35.                 } 
  36.  
  37.                 return view; 
  38.             } else { 
  39.                 throw new IllegalArgumentException("ViewStub must have a valid layoutResource"); 
  40.             } 
  41.         } else { 
  42.             throw new IllegalStateException("ViewStub must have a non-null ViewGroup viewParent"); 
  43.         } 
  44.     } 
责任编辑:赵宁宁 来源: 技术小黑屋
相关推荐

2013-01-08 16:05:23

Android开发布局ViewStub

2013-01-08 13:46:58

Android开发ViewStub布局

2009-08-05 15:13:32

使用Cache提高AS

2020-07-13 13:00:24

CSS变量技巧

2020-08-28 10:22:26

前端布局效率

2022-05-30 10:28:04

FlatBuffer数据可视化

2009-11-02 14:08:05

2011-07-08 17:49:38

WITH ASCTE

2011-04-02 13:37:05

SQL Server 索引视图

2021-07-14 14:06:06

CSS前端浏览器

2011-04-11 14:56:09

Oracle性能

2018-07-19 15:57:46

ViewStub源码方法

2017-12-29 15:16:28

2009-04-14 14:53:06

C++Lambda函数多线程

2011-03-24 09:03:13

Android SDKAndroid

2015-10-14 17:27:18

性能

2011-05-24 15:15:12

mysql性能

2009-12-23 17:07:37

WPF性能

2015-10-10 11:00:05

RubyRails性能

2019-04-03 13:00:27

CSSBFC前端
点赞
收藏

51CTO技术栈公众号