使用 ViewStub 延迟加载布局

本文介绍了如何使用 ViewStub 进行延迟加载布局,以优化应用性能。相较于动态添加 View,ViewStub 提供了更为优雅的解决方案,特别是在处理如'点击查看更多'等场景时。文中提到,只有在用户需要时才调用 ViewStub.inflate(),从而减少资源浪费,尤其是在 ListView 或 RecyclerView 中。同时,文章指出虽然性能提升可能不明显,但在处理重量级操作时,懒加载能带来好处。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前

在某些场景下(比如,某个“点击查看更多”的情形),对于不需要在最开始时就展现的 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

关于数据绑定

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值