1、自定义 RecyclerView

public class CustomRecyclerView extends RecyclerView {
    private static final String SAVED_SUPER_STATE = "super-state";
    private static final String SAVED_LAYOUT_MANAGER = "layout-manager-state";
    private Parcelable mLayoutManagerSavedState;
    public CustomRecyclerView(@NonNull Context context) {
        super(context);  
    }

    public CustomRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);  
    }

    public CustomRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 保存数据状态
     * @return
     */
    @Override
    protected Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(SAVED_SUPER_STATE, super.onSaveInstanceState());
        bundle.putParcelable(SAVED_LAYOUT_MANAGER, Objects.requireNonNull(this.getLayoutManager()).onSaveInstanceState());
        return bundle;
    }

    /**
     * 恢复数据状态
     * @param state
     */
    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            mLayoutManagerSavedState = bundle.getParcelable(SAVED_LAYOUT_MANAGER);
            state = bundle.getParcelable(SAVED_SUPER_STATE);
        }
        super.onRestoreInstanceState(state);
    }
    /**
     * 配置更改后恢复滚动位置
     * 必须在设置适配器后调用
     */
    private void restorePosition() {
        if (mLayoutManagerSavedState != null) {
            Objects.requireNonNull(this.getLayoutManager()).onRestoreInstanceState(mLayoutManagerSavedState);
            mLayoutManagerSavedState = null;
        }
    }

    /**
     * 设置适配器数据
     * @param adapter
     */
    @Override
    public void setAdapter(Adapter adapter) {
        super.setAdapter(adapter);
        restorePosition();
    }
}

2、Activity 或者 Fragment使用RecyclerView数据状态保存和恢复

private Parcelable state;
@Override
public void onPause() {
    super.onPause();
    // 保存RecyclerView数据状态
    state = Objects.requireNonNull(recyclerView.getLayoutManager()).onSaveInstanceState();
}

    @Override
public void onResume() {
    super.onResume();
    // 恢复RecyclerView数据状态
    Objects.requireNonNull(recyclerView.getLayoutManager()).onRestoreInstanceState(state);
}
最后修改:2022 年 01 月 13 日
如果觉得我的文章对你有用,请随意赞赏