RecyclerView保存状态

时间:2014-12-02 18:48:15

标签: android android-recyclerview

任何人都有问题,在更改方向后,RecyclerView不会保存滚动位置?

mMyAdapter = new MyAdapter(context, MyAdapter.generateKey(this), savedInstanceState);
mMyAdapter.setHasStableIds(true);

mLayoutManager = new LinearLayoutManager(context, VERTICAL, false);
int padding = ResourceUtils.dp2px(context, 8);
mRecycleView.setClipToPadding(false);
mRecycleView.setPadding(0, ResourceUtils.getPixelSize(R.dimen.toolbar_height), 0, padding);
mRecycleView.setOverScrollMode(View.OVER_SCROLL_ALWAYS);
mRecycleView.setLayoutManager(mLayoutManager);
mRecycleView.setAdapter(MyAdapter);
mRecycleView.setHasFixedSize(false);
mRecycleView.setOnScrollListener(mScrollManager); // only to hide Toolbar on scroll

所以我没有修改onDestroyOnSaveInstanceState方法,只保存适配器数据,所以当我转动手机时,滚动RecyclerView重置的位置,有些建议?

2 个答案:

答案 0 :(得分:2)

最近,我为所有RecyclerView改进并创建了 FlexibleAdapter 模式。它能够在旋转后保持状态。

使用非常简单,只需在公共文件中复制2个类+一些xml,以便像ListView一样启用选择(单个/多个)。

请查看说明和完整的工作示例:https://github.com/davideas/FlexibleAdapter

答案 1 :(得分:1)

我明白了我的错误,我使用了来自

RecyclerView
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    //used this instance of recycler view
    mRecyclerView = inflater.inflate(R.layout.recycle_fragment, container, false);
    return mRecyclerView;
}

但需要

 @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // instead of searching it after view created
        mRecycleView = ButterKnife.findById(getView(), R.id.recycler_view);
}

问题解决了