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将为空。