Skip to content

Instantly share code, notes, and snippets.

@raymondctc
Last active December 18, 2017 03:27
Show Gist options
  • Save raymondctc/f6ef2d69ad923c0ca622d1be95dcb3c7 to your computer and use it in GitHub Desktop.
Save raymondctc/f6ef2d69ad923c0ca622d1be95dcb3c7 to your computer and use it in GitHub Desktop.
public abstract class BaseViewStubFragment extends Fragment {
private Bundle mSavedInstanceState;
private boolean mHasInflated = false;
private ViewStub mViewStub;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_viewstub, container, false);
mViewStub = (ViewStub) view.findViewById(R.id.fragmentViewStub);
mViewStub.setLayoutResource(getViewStubLayoutResource());
mSavedInstanceState = savedInstanceState;
if (getUserVisibleHint() && !mHasInflated) {
View inflatedView = mViewStub.inflate();
onCreateViewAfterViewStubInflated(inflatedView, mSavedInstanceState);
afterViewStubInflated(view);
}
return view;
}
protected abstract void onCreateViewAfterViewStubInflated(View inflatedView, Bundle savedInstanceState);
/**
* The layout ID associated with this ViewStub
* @see ViewStub#setLayoutResource(int)
* @return
*/
@LayoutRes
protected abstract int getViewStubLayoutResource();
/**
*
* @param originalViewContainerWithViewStub
*/
@CallSuper
protected void afterViewStubInflated(View originalViewContainerWithViewStub) {
mHasInflated = true;
if (originalViewContainerWithViewStub != null) {
View pb = originalViewContainerWithViewStub.findViewById(R.id.inflateProgressbar);
pb.setVisibility(View.GONE);
}
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && mViewStub != null && !mHasInflated) {
View inflatedView = mViewStub.inflate();
onCreateViewAfterViewStubInflated(inflatedView, mSavedInstanceState);
afterViewStubInflated(getView());
}
}
// Thanks to Noa Drach, this will fix the orientation change problem
@Override
public void onDetach() {
super.onDetach();
mHasInflated = false;
}
}
@UmarBhutta
Copy link

Can you explain that V.gV(view, R.id.fragmentViewStub) ?

Copy link

ghost commented Sep 15, 2017

@raymondctc Thanks for gist, very helpful .
@UmarBhutta I think it is as mViewStub = view.findViewById(R.id.fragmentViewStub);

@raymondctc
Copy link
Author

Updated to avoid confusion

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