将光标移到/点击文章中的句子上,可以查看译文。      显示繁体中文内容    显示简体中文内容

android - How to save RecyclerView's scroll position using RecyclerView.State?
android如何使用 RecyclerView.State 保存RecyclerView位置的滚动?

54 1

I have a question about Android's RecyclerView.State.

I am using a RecyclerView, how could i use and bind it with RecyclerView.State?

My purpose is to save the RecyclerView's scroll position.

时间: 原作者:

145 4

How do you plan to save last saved position with RecyclerView.State?

You can always rely on ol 'good save state.Extend RecyclerView and override onSaveInstanceState() and 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];


 }


 };


 }



原作者:
...