Last active
December 18, 2017 03:27
-
-
Save raymondctc/f6ef2d69ad923c0ca622d1be95dcb3c7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
@raymondctc Thanks for gist, very helpful .
@UmarBhutta I think it is as mViewStub = view.findViewById(R.id.fragmentViewStub);
Updated to avoid confusion
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you explain that V.gV(view, R.id.fragmentViewStub) ?