Android,如何保存Fragment的状态

Stack Overflow对此问题的讨论这里

Save state in fragment

在Fragment里面,利用onSaveInstanceState保存数据,并可在onActivityCreated里面恢复数据。

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ...
    if (savedInstanceState != null) {
        // Restore the fragment's state here
    }
}

public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    // Save the fragment's state here
}

Save state in Activity

接下来重点是,在Activity里面,利用onSaveInstanceState保存Fragment实例的数据,并可在onCreate里面恢复数据。

private Fragment myFragment;

public void onCreate(Bundle savedInstanceState) {
    ...
    if (savedInstanceState == null) {
        // Instantiate fragment
    } else {
        // Restore the fragment's instance
        myFragment = getSupportFragmentManager().getFragment(
                    savedInstanceState, "fragment");
    }
    ...
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    //Save the fragment's instance
    // fragment instance may be null
    if (myFragment != null) {
        getSupportFragmentManager().putFragment(outState, "fragment", myFragment);
    }
}

End

最后,不要忽略状态保存的问题,在内存不足或者系统限制比较苛刻的机器上面,都有可能出现Fragment或Activity被回收,比如经常出现拍照之后返回App,但App里面的数据被清空了,更常见的就是旋转屏幕,所以要保存好自己需要的数据。

转载请附上本文地址

    原文作者:SoloHo
    原文地址: https://www.jianshu.com/p/580ec2951c39
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞