无法在RecyclerView中保存状态

时间:2017-03-17 13:02:53

标签: android android-fragments android-recyclerview

当我从另一个片段返回此片段时,我无法恢复水平RecyclerView的滚动位置。所以我有一个主垂直RecyclerView,里面有几个水平的RecyclerViews。我需要保存这些内部列表的位置。这是我的片段,我保存状态:

 @Override
    public void onPause() {
        super.onPause();

        if (outState == null){
            outState = new Bundle();
        }
        // saves the positions in lists
        Map<String, Parcelable> states = mainVideoAdapter.saveSubListState();
        Iterator it = states.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            outState.putParcelable((String) pair.getKey(), (Parcelable) pair.getValue());

        }

    }

以下是我调用onSaveInstanceState()(适配器)的代码:

Map<String, Parcelable> states;
    public Map<String, Parcelable> saveSubListState(){
        states = new HashMap<>();
        for (int i = 0; i < mainItems.size(); i++) {
            if (!mainItems.get(i).isSliding()){
                String key = mainItems.get(i).getGenreEntity().getId();
                if (recyclerViews.get(key) != null){
                    states.put(key, recyclerViews.get(key).getLayoutManager().onSaveInstanceState());
                }
            }
        }

        return states;
    }

在这里,我在Fragment中检索这个状态:

Bundle outState;
    @Override
    public void onResume() {
        super.onResume();

        if (outState != null){
            Map<String, Parcelable> states = mainVideoAdapter.getStates();
            if (states != null && !states.isEmpty()){
                Iterator it = states.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry pair = (Map.Entry) it.next();
                    Parcelable savedRecyclerLayoutState = outState.getParcelable((String) pair.getKey());
                    mainVideoAdapter.getRecyclerViews().get(pair.getKey())
                            .getLayoutManager().onRestoreInstanceState(savedRecyclerLayoutState);
                    it.remove(); // avoids a ConcurrentModificationException
                }
            }
        }    

    }

我做错了什么?

1 个答案:

答案 0 :(得分:3)

我认为你应该在放置Recyclerview的片段中这样做。

View mView; // declare it globally

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       if(mView == null){ // it will not reload Recyclerview it will set first time view which is loaded. 
          mView = inflater.inflate(R.layout.yourview, null);
        }
        return rootView;
    }
  每次导航回该片段时,

片段onCreateView()都会调用。因此,首次初始化View,此Recyclerview状态将保持不变。

希望这个帮助