Activity销毁时Tablayout+Viewpager+Fragment状态保存

前言

在项目研发时,遇到屏幕旋转或改变系统字体后返回App等需求,ViewPager+Fragment布局时,控件为空,数据也没了。这就涉及到Fragment的状态保存。

使用

使用Fragment时就必定会用到FragmentManager,在FragmentManager中有两个抽象方法:

  1. getFragment(Bundle bundle, String key)
  2. putFragment(Bundle bundle, String key, Fragment fragment)

抽象方法getFragment实现类下的源码为:

public void putFragment(Bundle bundle, String key, Fragment fragment) {
    if (fragment.mIndex < 0) {
        throwException(new IllegalStateException("Fragment " + fragment+ " is not currently in the FragmentManager"));
    }
    bundle.putInt(key, fragment.mIndex);
}

抽象方法putFragment实现类下的源码为:

public Fragment getFragment(Bundle bundle, String key) {
    int index = bundle.getInt(key, -1);
    if (index == -1) {
        return null;
    }
    if (index >= mActive.size()) {
        throwException(new IllegalStateException("Fragment no longer exists for key "+ key + ": index " + index));
    }
    Fragment f = mActive.get(index);
    if (f == null) {
        throwException(new IllegalStateException("Fragment no longer exists for key "+ key + ": index " + index));
    }
    return f;
}

从源码中发现key是为了区分保存在Bundle中的Fragment的,因而key可以随意命名,但是获取和保存的必须一致。
onSaveInstanceState(Bundle outState)中调用putFragment保存Fragment
onCreate(Bundle savedInstanceState)中调用getFragment获取Fragment

最后

欢迎下载源码,源码中有对FragmentPagerAdapter抽取封装了一个基类,方便项目中使用。
源代码

你可能感兴趣的:(Activity销毁时Tablayout+Viewpager+Fragment状态保存)