android - android如何使用 RecyclerView.State 保存RecyclerView位置的滚动?

  显示原文与译文双语对照的内容
54 1

我有一个关于 RecyclerView.State的的问题。

我正在使用 RecyclerView,如何使用 RecyclerView.State 并将它的绑定到?

我的目的是为了节省recyclerview位置的

时间: 原作者:

145 4

你打算如何将上次保存的位置保存为 RecyclerView.State

你总是可以依赖 ol save 。 扩展 RecyclerView 并重写 onSaveInstanceState() 和 onRestoreInstanceState():


@Override


 protected Parcelable onSaveInstanceState() {


 Parcelable superState = super.onSaveInstanceState();


 LayoutManager layoutManager = getLayoutManager();


 if(layoutManager!= null && layoutManager instanceof LinearLayoutManager){


 mScrollPosition = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();


 }


 SavedState newState = new SavedState(superState);


 newState.mScrollPosition = mScrollPosition;


 return newState;


 }



 @Override


 protected void onRestoreInstanceState(Parcelable state) {


 super.onRestoreInstanceState(state);


 if(state!= null && state instanceof SavedState){


 mScrollPosition = ((SavedState) state).mScrollPosition;


 LayoutManager layoutManager = getLayoutManager();


 if(layoutManager!= null){


 int count = layoutManager.getChildCount();


 if(mScrollPosition!= RecyclerView.NO_POSITION && mScrollPosition <count){


 layoutManager.scrollToPosition(mScrollPosition);


 }


 }


 }


 }



 static class SavedState extends android.view.View.BaseSavedState {


 public int mScrollPosition;


 SavedState(Parcel in) {


 super(in);


 mScrollPosition = in.readInt();


 }


 SavedState(Parcelable superState) {


 super(superState);


 }



 @Override


 public void writeToParcel(Parcel dest, int flags) {


 super.writeToParcel(dest, flags);


 dest.writeInt(mScrollPosition);


 }


 public static final Parcelable.Creator<SavedState> CREATOR


 = new Parcelable.Creator<SavedState>() {


 @Override


 public SavedState createFromParcel(Parcel in) {


 return new SavedState(in);


 }



 @Override


 public SavedState[] newArray(int size) {


 return new SavedState[size];


 }


 };


 }



原作者:
...