ViewStub的使用(性能优化)

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:


The ViewStub thus defined can be found using the id "stub." After inflation of the layout resource "mySubTree," the ViewStub is removed from its parent. The View created by inflating the layout resource "mySubTree" can be found using the id "subTree," specified by the inflatedId property. The inflated View is finally assigned a width of 120dip and a height of 40dip. The preferred way to perform the inflation of the layout resource is the following: ViewStub stub = (ViewStub) findViewById(R.id.stub); View inflated = stub.inflate(); When inflate() is invoked, the ViewStub is replaced by the inflated View and the inflated View is returned. This lets applications get a reference to the inflated View without executing an extra findViewById().

我们用ViewStub来实现视图的懒加载。比如,当我们的应用在打开的时候,有一些视图是不需要可见的,我们把它们的Visibility属性设置为不可见后,在加载视图时系统还是会把不可见的视图一同加载,一次性加载复杂的视图可能会导致应用出现卡顿。ViewStub可以解决这个问题,它是一个“空”控件,视图加载时并不会真正加载它指定的视图,而是到了需要加载的时候由工程师手动加载。

如下。

像上面这样写,我们设定了它的视图layout属性,但这只是制造了一个空壳,这一个空壳允许我们手动的控制它的加载(在这个视图加载前,它是不可见的)。

需要注意的是,viewStub控件只需要被加载一次,可以通过isInflated()方法判断是否已经加载过,随后通过inflate()方法对视图进行加载,用这一个方法后,viewStub指定的layout就会实现加载变可见。加载代码如下。


viewStub也支持加载时的监听,以下是对某个viewStub的加载监听操作。

通过判断viewStub的parent是否为空,来判断ViewStub是否已经加载。原因是viewStub一旦加载,viewStub将脱离当前的布局,动态加载出来视图将会替换它的位置,所以加载后的viewStub的parent view将为空。

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

推荐阅读更多精彩内容

  • (1)什么时候使用ViewStub?为什么使用ViewStub? 当我们需要根据某个条件控制某个View的显示或者...
    CnPeng阅读 53,141评论 21 84
  • 引言:一个可用于性能优化的控件。时间:2017年09月21日作者:JustDo23Github:https://g...
    JustDo23阅读 6,333评论 4 5
  • 引言 相信在开发Android App的过程中,我们会常常遇到这样的业务需求,需要在运行时根据数据动态决定显示或隐...
    CrazyMO_阅读 959评论 0 2
  • Lambda表达式可以理解为一种匿名函数;没有名称,有参数列表、函数主题、返回类型,可能还有一个可以抛出的异常列表...
    热爱生活的舒舒阅读 293评论 0 0
  • “山上海棠花开了,这时节定是美得紧的。” 你倚在床头,看着窗外,嘴角边含笑。 “我去摘几朵,放在这儿。” 你的眼睛...
    秋解书阅读 450评论 3 3