androidandroid-inflateviewstub

ViewStub parent goes null


I have a ViewHolder that contains a ViewStub, when I want to bind data into my view, I first check that is viewStub inflated before or not?

if (mViewStub != null) //still not inflated

then if mViewStub still not inflated, I try to inflate this by:

LinearLayout root = ((LinearLayout) mViewStub.inflate());

but here I get Exception:

java.lang.IllegalStateException: ViewStub must have a non-null ViewGroup viewParent

I checked this answer and found that this exception will be thrown when the parent of ViewStub is null. By debugging, I find that it's true and the parent of my mViewStub was null.

the xml file is simple like this:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/root_view"
     android:layout_width="60dp"
     android:layout_height="100dp"
>

    <ViewStub
        android:id="@+id/view_cell_stub"
        android:layout="@layout/item_card"
        android:layout_width="60dp"
        android:layout_height="100dp"/>

</FrameLayout>

I must mention that ViewStub object does not create in runtime and I just find that by Id in ViewHolder class.

ViewStub mViewStub = itemView.findViewById(R.id.view_cell_stub);

Finally, after this explanation, my main question is "why the parent of mViewStub goes null"?


Solution

  • I see the source code of ViewStub from here and I found this exception only be thrown when the parent is null or parent is not an instance of ViewGroup.

    So I reviewed my code again and I found that when I inflate the XML and pass the view to the viewHolder, still view not have been added to root so the parent is null.

    I have been forced to replace ViewStub with the custom layout that I implement by myself.