Skip to content

Instantly share code, notes, and snippets.

@sbelloz
Last active September 3, 2021 16:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbelloz/2f5504974b7bfc7d947801a86f8725da to your computer and use it in GitHub Desktop.
Save sbelloz/2f5504974b7bfc7d947801a86f8725da to your computer and use it in GitHub Desktop.
Deflate the lazy view previously inflated, and reinflate a new ViewStub
public class ViewStubExt {
/**
* Deflates the view inflated by {@link ViewStub#inflate()}
* and replace it with a new {@link ViewStub} in its parent.
*
* @param view the view lazily inflated previously
* @return the new ViewStub with backed parameters
*
*/
public static ViewStub deflate(View view) {
ViewParent viewParent = view.getParent();
if (viewParent != null && viewParent instanceof ViewGroup) {
int index = ((ViewGroup) viewParent).indexOfChild(view);
if (index >= 0) {
int inflatedId = view.getId();
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
((ViewGroup) viewParent).removeView(view);
Context context = ((ViewGroup) viewParent).getContext();
ViewStub viewStub = new ViewStub(context);
viewStub.setInflatedId(inflatedId);
viewStub.setLayoutParams(layoutParams);
((ViewGroup) viewParent).addView(viewStub, index);
return viewStub;
} else {
throw new IllegalArgumentException("ViewStub must have a valid layoutResource");
}
} else {
throw new IllegalStateException("ViewStub must have a non-null ViewGroup viewParent");
}
}
private ViewStubExt() {
}
}
/**
* Deflates the view inflated by [ViewStub.inflate]
* and replace it with a new [ViewStub] in its parent.
*
* @return the new ViewStub with backed parameters
*/
fun ViewStub.deflate(): ViewStub {
val viewParent = parent
if (viewParent != null && viewParent is ViewGroup) {
val viewStub = ViewStub(context).apply {
inflatedId = this@deflate.inflatedId
layoutParams = this@deflate.layoutParams
}
val index = viewParent.indexOfChild(this)
viewParent.removeView(this)
viewParent.addView(viewStub, index)
return viewStub
} else {
throw IllegalStateException("Inflated View has not a parent")
}
}
@02gaurav
Copy link

02gaurav commented Sep 3, 2021

Does this work ? Its not working for me, I have viewstub inside SwipeRefreshLayout , I want to change the viewstub layout content on refresh but its showing nothing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment