Here's some code that deflates a view stub:
private Boolean isErrorViewInflated = false;
private ViewStub errorViewStub;
/* here a method that gets a view. If the view is already inflated,
* it uses that view, else it inflates the view. It also creates a viewStub
* object which will be used to replace the inflated view when it needs to
* be deflated.
/
public RelativeLayout getErrorView() {
RelativeLayout errorView = null;
if (isErrorViewInflated) {
errorView = activity.findViewById(R.id.error_view);
} else {
ViewStub stub = activity.findViewById(R.id.error_view_stub);
errorView = (RelativeLayout) stub.inflate();
errorViewStub = new ViewStub(getContext(), stub.getLayoutResource());
isErrorViewInflated = true;
}
return errorView;
}
/* Here's the code that deflates an inflated ErrorView back to a ViewStub
*/
private void deflateErrorView() {
if (isErrorViewInflated) {
RelativeLayout errorView = activity.findViewById(R.id.error_view);
ViewGroup parent = (ViewGroup)errorView.getParent();
int index = parent.indexOfChild(errorView);
parent.removeView(errorView);
parent.addView(errorViewStub, index);
isErrorViewInflated = false;
}
}
If you're wondering, you can't just cache the original ViewStub and use it to replace the inflated view. That's because the original ViewStub object had a parent View and you get an error if you try to add that view into any view group (even if it's the same view group it was originally contained in). So, the way around this issue is to create a new ViewStub object using the same layout resource as in the original ViewStub.
If you're not concerned about the space occupied by an inflated ViewStub when that inflated ViewStub is no longer needed, then the "View.GONE" solution is fine. There's no significant runtime overhead for views whose visibility is set to GONE. In my case, I've been using ViewStub's for errors, logs and console display areas and I want the system to be able to garbage collect the objects associate with those views when they are not in use.
setVisibility(View.GONE)
is a bit more descriptive. – Duer