Created
March 24, 2015 02:48
-
-
Save boxme/0f76591d109659daec42 to your computer and use it in GitHub Desktop.
BaseFragment that all Fragments should extend from in order to save state in all circumstances using argument
This file contains 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 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