Skip to content

Instantly share code, notes, and snippets.

@BCsl
Last active March 27, 2017 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BCsl/30b4ff6e40d46843345af1d85117d844 to your computer and use it in GitHub Desktop.
Save BCsl/30b4ff6e40d46843345af1d85117d844 to your computer and use it in GitHub Desktop.
/**
* 在内存重启的时候自动恢复可见状态的Fragment,避免重叠现象
* 但同时不要忘了在Activity中判断`savedInstanceState`为null的时候才操作Fragment
* Created by chensuilun on 16-8-9.
*/
public abstract class BaseRestoreFragment extends Fragment {
public static final String IS_SHOW = "is_show";
protected View mRootView;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (BuildConfig.DEBUG) {
Log.d(getClass().getSimpleName(), "onCreate:");
}
if (savedInstanceState != null && getFragmentManager() != null) {
boolean isShow = savedInstanceState.getBoolean(IS_SHOW, true);
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (BuildConfig.DEBUG) {
Log.d(this.getClass().getSimpleName(), "restore show:" + isShow);
}
if (!isShow) {
ft.hide(this);
} else {
ft.show(this);
}
ft.commit();
//是否从内存重启恢复后,并隐藏自己,某些情况下,可能在某个生命周期执行时(如onResume),进行动画等只是在用户操作界面之前才执行的初始化操作,这时候可以根据这个值来判断是否进行这些操作
setUserVisibleHint(isShow);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(IS_SHOW, !isHidden());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (BuildConfig.DEBUG) {
Log.d(getClass().getSimpleName(), "onCreateView:");
}
mRootView = onCreateContentView(inflater, container, savedInstanceState);
return mRootView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (BuildConfig.DEBUG) {
Log.v(getClass().getSimpleName(), "onViewCreated: ");
}
initView(view);
initData();
}
@Override
public void onStop() {
super.onStop();
if (BuildConfig.DEBUG) {
Log.d(getClass().getSimpleName(), "onStop: ");
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (BuildConfig.DEBUG) {
Log.d(getClass().getSimpleName(), "onDestroyView ");
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (BuildConfig.DEBUG) {
Log.d(getClass().getSimpleName(), "onDestroy: ");
}
}
protected abstract View onCreateContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);
protected abstract void initView(View root);
protected abstract void initData();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment