0

我在一个活动(比如 A1)中创建了一个简单的回收器视图,用户可以在其中添加/删除回收器视图中的项目。我现在正试图在导航到第二个活动(例如 A2)时保存它并在返回时恢复它(A2 -> A1),但我无法这样做。从 A2 回到 A1 时,回收器视图再次初始化,丢失所有用户修改的数据。请求您的帮助。

我已经尝试过 onSaveInstanceState 和 onRestoreInstanceState 方法,但是当我导航到 A1 时,没有调用 onRestoreInstanceState。我似乎无法弄清楚这一点。任何帮助,将不胜感激。

我的代码:


//rv is the recycler view I am trying to save
//STATE_KEY and TAG are strings for Log statement

Parcelable rv_state;

protected void onSaveInstanceState(Bundle state) {
        super.onSaveInstanceState(state);

        rv_state = rv.getLayoutManager().onSaveInstanceState();
        state.putParcelable(STATE_KEY, rv_state);
        Log.d(TAG, " on save rvstate setup = " + rv_state); //rv_state not null here
    }

    protected void onRestoreInstanceState(Bundle state) { //never called
        super.onRestoreInstanceState(state);
        Log.d(TAG, "b4 onRestoreinstance state check " + state);
        if (state != null)
            Log.d(TAG, "onRestoreinstance in if state check " + state);
        rv_state = state.getParcelable(STATE_KEY);
    }

@Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "b4 onResume rv_state check " + rv_state); //rv_state is always null
        if (rv_state != null) {
            Log.d(TAG, "in onResume rv_state check");
            rv.getLayoutManager().onRestoreInstanceState(rv_state);
        }
    }
4

0 回答 0