安卓系统是否会自动保存和恢复某些字段的实例状态?

问题描述 投票:0回答:1

我有一个RecyclerView,其中MyItem作为保存RecyclerView中每行的数据,一切都能正确实现,工作正常。

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder>{
    protected final List<MyItem> items= new ArrayList<>();
    public MyAdapter (List<RVItem> list) {
        if (list != null) {
            items.addAll(list);
        }
    }
}

而List items是由另一个对象传递过来的。

public class MyObject{
    private String otherThing;
    private List<MyItem> items;
    public someMethodToInitItems() {
        items = new ArrayList<>();
        items.add(...);
        items.add(...);
    }
    public createFragment() {
        Fragment f = new MyCustomFragment();
        f.setAdapter(new MyAdapter(items));
        // replace commit fragment...
    }
}

这里的问题是,当我的Activity被恢复时,字段 private List<MyItem> itemsMyObject 也神奇地恢复了,但像田野这样的 otherThing 仍然是空的,而且没有得到恢复.仅供参考,我没有明确地保存和恢复 items 无论如何,。还有: onSaveInstanceStateMyCustomFragment 是没有被触动的,也没有被super覆盖。

下面是我尝试从Activity中保存和恢复Fragment状态的方法。就是这样的。

public class MyActivity{
    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        getSupportFragmentManager().putFragment(outState, tag, getLastFragment());
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState != null) {
            Fragment fg = getSupportFragmentManager().getFragment(savedInstanceState, tag);
        }
    }
}

所以,我不明白。是安卓系统做了这个工作吗?保存和恢复字段 itemsMyObject 自动的?或者一定是有其他原因导致这种行为。

android android-activity android-savedstate
1个回答
0
投票

你需要覆盖onRetainNonConfigurationInstance方法。这个方法可以帮助你存储你的数据

更多详情 此处

© www.soinside.com 2019 - 2024. All rights reserved.