Android ViewSub惰性加载或延时加载

什么是ViewSub,下面是官方说明

A ViewStub is an invisible, zero-sized View that can be used to 
lazily inflate layout resources at runtime. When a ViewStub is made 
visible, or when inflate() is invoked, the layout resource is inflated. 
The ViewStub then replaces itself in its parent with the inflated View 
or Views. Therefore, the ViewStub exists in the view hierarchy until 
setVisibility(int) or inflate() is invoked. The inflated View is added 
to the ViewStub's parent with the ViewStub's layout parameters. 
Similarly, you can define/override the inflate View's id by using the 
ViewStub's inflatedId property. For instance:

简单的翻译下:
ViewStub是一个不可见的零大小的视图,可用于在运行时延迟加载布局资源。 当ViewStub变为可见时,或者当调用inflate()时,布局资源会加载进来。 然后,ViewStub在其父级中用加载进来的布局替换自身。 因此,ViewStub存在于视图层次结构中,直到调用setVisibility(int)或inflate()。 加载进来的视图被添加到ViewStub的父视图和ViewStub的布局参数。 类似地,您可以使用ViewStub的inflatedId属性定义/覆盖inflate View的id。

简单的总结

1.ViewStub 是一个轻量级的View,没有尺寸,不绘制任何东西,因此绘制或者移除时更省时。(ViewStub不可见,大小为0)

2.优点是实现View的延迟加载,避免资源的浪费,减少渲染时间,在需要的时候才加载View

3.缺点是ViewStub所要替代的layout文件中不能有标签
ViewStub在加载完后会被移除,或者说是被加载进来的layout替换掉了。

如何使用呢?

第一步声明ViewSub和需要加载的进来的布局layout_arrange_view12


layout_arrange_view12里面的内容,可根据自己需求写




    

这里inflatedId有什么作用呢?

一旦ViewStub visible/inflated,则ViewStub将从视图框架中移除,其id viewSubArrange 也会失效
ViewStub被绘制完成的layout文件取代,并且该layout文件的root view的id是android:inflatedId指定的id viewInfalatedRootId,root view的布局和ViewStub视图的布局保持一致。

第二步

if (mArrangeView==null) {
            viewSubArrange.inflate();
            //ViewSub在visible/inflated后会被移除,但不为null,实列的引用保存在mArrangeView
            //inflatedId指定的id的布局和ViewStub视图的布局保持一致
            View rootView = findViewById(R.id.viewInfalatedRootId);
            //或者 View rootView = viewSubArrange.findViewById(R.id.viewInfalatedRootId);

            //惰性加载后查找控件id
            //1.mArrangeView = (Arrange12View) viewSubArrange.findViewById(R.id.arrangeview);
            //viewSubArrange.findViewById结果为null
            
            //2.rootView.findViewById结果为null
            //mArrangeView = (Arrange12View) rootView.findViewById(R.id.arrangeview);

            //3.正确的方式this.findViewById,
            mArrangeView=(Arrange12View) findViewById(R.id.arrangeview); 
            //When inflate() is invoked, the ViewStub is replaced by the 
            //inflated View and the inflated View is returned
            //上面是官方文档的说明,估计viewSubArrange并不是returned View的父布局
        }

这里为什么要用if (mArrangeView==null)判断呢,因为ViewSub只能实例化一次,不然会报如下异常:

java.lang.IllegalStateException: ViewStub must have a non-null 
ViewGroup viewParent

以上是我的简单理解,有偏差的地方希望留言指正,O(∩_∩)O谢谢

你可能感兴趣的:(Android ViewSub惰性加载或延时加载)