您的位置:首页 > 其它

使用 ViewStub 延迟加载布局

2016-06-12 23:50 344 查看

之前

在某些场景下(比如,某个“点击查看更多”的情形),对于不需要在最开始时就展现的 View,可以进行 Lazy loading 处理,以优化应用体验。之前我想到的方法是使用 Java 代码动态地向布局中 addView,然而比起写 XML Layout,这种方法略显繁琐;而且违反我尽量在 XML 中写 UI 层的习惯XD。

依然以“点击查看更多”举例,如果用户点开“更多”的概率并不大,而且“更多”中包含很多重量级的操作,则懒加载会显得更加必要。最常用的 findViewById 就是一个很重的操作,它是遍历 id 来查找所需 View 的。如果这些重量级操作发生在 ListView / RecyclerView 中,则会进一步造成无用的资源浪费。

比 addView 更优雅

说的就是 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:

<ViewStub android:id="@+id/stub"
android:inflatedId="@+id/subTree"
android:layout="@layout/mySubTree"
android:layout_width="120dip"
android:layout_height="40dip" />


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.inflate(),而后再进行 findViewById 等后续操作。

DISCLAIMER

没做 Performance Profiling Test、Benchmark Test,关于性能提升是我脑补的。在被懒加载的操作比较轻量时,应该看不到什么效果。

特别地,如果只有一个 View 需要懒加载,直接 setVisibility 可能更简单。

SEE ALSO

关于数据绑定
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: