使用 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
关于数据绑定相关文章推荐
- 指针
- 好的用户体验的网站怎么策划?
- 狗狗们来袭!分享一个独立小游戏,狗狗后院!
- SQL Server 2008 parseJSON函数将JSON解析成Table
- Linux进程关系
- js的闭包解决百度地图的信息窗口问题
- ActionBar
- 在Android中调用C#写的WebService(附源代码)
- 指针与引用
- android中gravity和layout_gravity的区别
- opencv第四课----smooth函数使用(提出几个课后作业,希望完成)
- Tensorflow 问题
- Android——JDK的get请求方式
- spring 入门实例--参照 spring in action 3 中的例子
- Mysql实用SQL语句总结(持续更新)
- (一)JAVA CPU占用过高问题排查(linux)
- 勇者斗恶龙
- iOS开发之百度免费API使用案例(身份证号获取地址、手机号查归属地、MD5解密等)
- Chapter 3. 数据检索(查询)---select、top...order by、distinct、where条件查询、分组查询、模糊查询、null处理
- linux命令和工具