E/AndroidRuntime: FATAL EXCEPTION: main Process: com.houtrry.viewstubdemo, PID: 4841 java.lang.IllegalStateException: ViewStub must have a non-null ViewGroup viewParent at android.view.ViewStub.inflate(ViewStub.java:292) at com.houtrry.viewstubdemo.MainActivity$1.onClick(MainActivity.java:28) at android.view.View.performClick(View.java:4785) at android.view.View$PerformClick.run(View.java:19884) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5343) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
@Override @android.view.RemotableViewMethod public void setVisibility(int visibility) { if (mInflatedViewRef != null) { View view = mInflatedViewRef.get(); if (view != null) { view.setVisibility(visibility); } else { throw new IllegalStateException("setVisibility called on un-referenced view"); } } else { super.setVisibility(visibility); if (visibility == VISIBLE || visibility == INVISIBLE) { inflate(); } } }
public View inflate() { final ViewParent viewParent = getParent();
if (viewParent != null && viewParent instanceof ViewGroup) { if (mLayoutResource != 0) { final ViewGroup parent = (ViewGroup) viewParent; final LayoutInflater factory; if (mInflater != null) { factory = mInflater; } else { factory = LayoutInflater.from(mContext); } final View view = factory.inflate(mLayoutResource, parent, false);
if (mInflatedId != NO_ID) { view.setId(mInflatedId); }
final int index = parent.indexOfChild(this); parent.removeViewInLayout(this);
final ViewGroup.LayoutParams layoutParams = getLayoutParams(); if (layoutParams != null) { parent.addView(view, index, layoutParams); } else { parent.addView(view, index); }
mInflatedViewRef = new WeakReference<View>(view);
if (mInflateListener != null) { mInflateListener.onInflate(this, view); }
return view; } else { throw new IllegalArgumentException("ViewStub must have a valid layoutResource"); } } else { throw new IllegalStateException("ViewStub must have a non-null ViewGroup viewParent"); } }
public void setOnInflateListener(OnInflateListener inflateListener) { mInflateListener = inflateListener; }
首先, 获取ViewStub的parent, 如果parent为空或者parent不是ViewGroup, 则抛出异常”ViewStub must have a non-null ViewGroup viewParent”, 我们先把问题放在这里, 继续向下看. mLayoutResource就是android:layout的值, 如果没有设置android:layout, 则抛出异常”ViewStub must have a valid layoutResource”. 接下来就是ViewStub的核心了.