ViewStub继承了View,非常轻量并且宽和高都是0,因此它本身不参与任何的布局和绘制的过程。它的意义在于按需加载所需要的布局文件。比如说阅读电子书的app,一般情况下很少用到本地导入,所以本地导入的view可以使用ViewStub,在点击了导入按钮之后再导入本地导入的布局。从而提高程序初始化的性能。
主布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ViewStub
android:id="@+id/stub_import"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inflatedId="@+id/panel_import"
android:layout="@layout/viewstub_text" />
</LinearLayout>
viewstub_text.xml需要加载的实际内容
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello ViewStub" />
</LinearLayout>
程序调用:
package com.example.wangjyfnst.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.widget.TextView;
/**
* Created by wangjy.fnst on 2016/9/28.
*/
public class ViewStubActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewstub);
((ViewStub) findViewById(R.id.stub_import)).inflate();
// 加载完毕之后直接获取TextView
TextView tv = (TextView) findViewById(R.id.tv_content);
tv.setText("修改啦");
// 加载完毕之后先通过inflatedId获取ViewStub布局,在获取TextView
View view = findViewById(R.id.panel_import);
TextView tv = (TextView) view.findViewById(R.id.tv_content);
tv.setText("修改啦2");
}
}
加载的方式既可以使用:
((ViewStub) findViewById(R.id.stub_import)).inflate();
也可以是:
((ViewStub) findViewById(R.id.stub_import)).setVisibility(View.VISIBLE);
加载之后,ViewStub就会被它内部的布局替换掉,这个时候ViewStub就不在是整个布局中的一部分,如果再获取ViewStub会出现空指针异常。另外目前ViewStub不支持<merge>标签。填充布局root布局如果有id,则会默认被android:inflatedId所设置的id取代,如果没有设置android:inflatedId,则会直接使用填充布局id。
上面获取TextView有两种方式,一种直接获取,另一种通过inflatedId获取,测试下来都可以。
ViewStub不适用于布局需要多次的显示和隐藏。
与include不同的是,加载布局使用的标签是android:layout="@layout/xxx"而不是include的layout="@layout/xxx"