How to check if a viewStub is already inflated?

15.1k Views Asked by At

I did not find any boolean method does this task. Can I do this by checking if the id of the viewStubchanged to the one specified as inflatedid?

Javacode:

    protected void plantViewTree() {
    // TODO Auto-generated method stub

        ViewStub mViewstub = (ViewStub) findViewById(R.id.viewStub00);

            if (mViewStub is inflated) {
              //do somthing
              }else
               mViewstub.inflate();

}

Update Comments on th eOutput

According to this code, the toast always displays its message, which mean since mViewStub is assigned to findViewById it is never null except the viewstub view in the underlaying alyout is not available. Any suggestions.?

protected void plantViewTree() {
    // TODO Auto-generated method stub
    ViewStub mViewstub = (ViewStub) findViewById(R.id.viewStub00);
    if (mViewstub != null)
        Toast.makeText(getApplicationContext(), "view is inflated", 
Toast.LENGTH_LONG).show();
    else
        mViewstub.inflate();
}
8

There are 8 best solutions below

1
On BEST ANSWER

We can view the ViewStub source code, the most important method is 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");
    }
}

Notice this line parent.removeViewInLayout(this) ,it had removed in layout after inflate.so we can check if a viewStub is already inflated by this way.

if (mViewStub.getParent() != null) {
    mViewStub.inflate();
} else {
    mViewStub.setVisibility(View.VISIBLE);
}
0
On
if (mViewStub.getParent() != null) { 
    //have not been inflated
    mViewStub.inflate();
} else { 
    //already inflated
}
1
On

note from google:

When a ViewStub is made visible, or when inflate() is invoked, the layout resource is inflated.

so you can check the visibility (or even checking if it's "null").

0
On

You can use this extension:

/**
 * To prevent crash when we try inflate view that was already inflated. Because OS delete ViewStub by inflating.
 */
fun ViewStub?.safeInflate() {
    if (this?.parent != null) inflate()
}
0
On

you can use this in Kotlin.. i know that it uses tag (its not cool) but its easy to use. this is kotlin extension function:

fun ViewStub.doInflate(init: View.() -> Unit = {}, action: (View) -> Unit = {}) {
val isInflated = (tag as? Boolean) ?: false
if (!isInflated) {
    setOnInflateListener { _, view ->
        this.tag = true
        init.invoke(view)
        action.invoke(view)
    }
    this.inflate()
} else {
    action.invoke(this.rootView)
}

}

and you can use it like this :

 myViewStub.doInflate({
            //code that run with initialisation
        }, {
           //code that run if stub already inflated
        })
0
On

A more simple approach, in Kotlin:

if (viewStub != null) {
   viewStub.isVisible = true
} else {
   // The view has been inflated already.
}
1
On

Calling yourViewStub.visibility(View.VISIBLE) you don´t need to check if it´s inflated or not.

0
On

As the documentation suggests, we should not keep a long lived reference to the ViewStub, and android also allows assigning an inflatedId to ViewStub, which comes into existence once its inflated

so we can have a function signature like getInflatedView(): View

fun getInflatedView(@LayoutRes layoutId: Int): View {
    val stub: ViewStub? = findViewById(R.id.stubId)
    stub?.layoutResource = layoutId
    return stub?.inflate() ?: findViewById(R.id.inflatedId)
}