Skip to content

Instantly share code, notes, and snippets.

@boxme
Created Mar 24, 2015
Embed
What would you like to do?
BaseFragment that all Fragments should extend from in order to save state in all circumstances using argument
public abstract class BaseFragment extends Fragment {
static final String STATE = "saved_state";
Bundle mSavedState;
public BaseFragment() {}
public abstract void refreshData();
protected void showSoftKeyboard(View editText) {
InputMethodManager imm =
(InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}
protected void hideSoftKeyboard(View editText) {
InputMethodManager imm =
(InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromInputMethod(editText.getWindowToken(), 0);
imm.hideSoftInputFromWindow(editText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
onSettingFragmentVariables(getArguments());
if (!restoreStateFromArguments()) {
onFirstTimeLaunched();
} else {
onRelaunched();
}
}
protected abstract void onFirstTimeLaunched();
protected abstract void onRelaunched();
@Override
public void onSaveInstanceState(Bundle outState) {
saveStateToArguments();
super.onSaveInstanceState(outState);
}
@Override
public void onDestroyView() {
saveStateToArguments();
super.onDestroyView();
}
private void saveStateToArguments() {
saveState();
Bundle bundle = getArguments();
bundle.putBundle(STATE, mSavedState);
}
private void saveState() {
if (mSavedState == null) {
mSavedState = new Bundle();
}
onSaveState(mSavedState);
}
protected abstract void onSaveState(Bundle outState);
private boolean restoreStateFromArguments() {
Bundle bundle = getArguments();
mSavedState = bundle.getBundle(STATE);
if (mSavedState != null) {
restoreState();
return true;
}
return false;
}
private void restoreState() {
if (mSavedState != null) {
onRestoreState(mSavedState);
}
}
protected abstract void onRestoreState(Bundle savedInstanceState);
protected abstract void onSettingFragmentVariables(Bundle args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment