1.第一种使用方式:
在xml布局中指定要膨胀的布局:
<ViewStub
android:id="@+id/statusBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout="@layout/base_view_status_bar" />
在代码中执行膨胀:
viewStub.inflate()
2.第二种使用方式:
不在xml中指定布局,在代码中动态指定layout布局:
viewStub.layoutResource = R.layout.xxx
viewStub.inflate()
3.第三种使用方式:
除了加载指定布局,我们可以通过反射加载指定的View对象:
ViewStub通过inflate()函数膨胀一个布局,那我们看看inflate()函数的源码:
public View inflate() {
final ViewParent viewParent = getParent();
if (viewParent != null && viewParent instanceof ViewGroup) {
if (mLayoutResource != 0) {
final ViewGroup parent = (ViewGroup) viewParent;
final View view = inflateViewNoAdd(parent);
replaceSelfWithView(view, parent);
mInflatedViewRef = new WeakReference<>(view);
if (mInflateListener != null) {
mInflateListener.onInflate(this, view);
}
return view;
} else {
throw new IllegalArgumentException("ViewStub must have a valid layoutResource