问题描述
我从这里得到了很多答案..但是没有一个答案可以解决我的问题..这就是为什么我要问这个问题.
I have followed so many answers from here.. but not a single one solving my issue .. that's why i am asking.
我想将滚动位置保存在一个片段中.他们在很多文章中建议遵循
I want to save scroll position in a fragment.In So many articles they have suggested to follow
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
和
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
但这两种方法在片段中不可用.
But this two method is not available in fragment.
我的代码:
private int mPositionIng = RecyclerView.NO_POSITION;
private String KEY_POSITION_ING = "KeyPositionIng";
在OnCreateView()
in OnCreateView()
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(KEY_POSITION_ING)) {
mPositionIng = savedInstanceState.getInt(KEY_POSITION_ING);
}
}
覆盖片段中的方法它们与上面的方法不同.我不知道我在哪里做错了.
Override Methods in fragment They are not same method as above. i don't know where i am doing wrong.
@Override
public void onSaveInstanceState(Bundle outState) {
int scrollPositionIng = mRecyclerViewIngredients.computeVerticalScrollOffset();
mPositionIng = scrollPositionIng;
outState.putInt(KEY_POSITION_ING, mPositionIng);
super.onSaveInstanceState(outState);
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
if (mPositionIng != RecyclerView.NO_POSITION) {
mRecyclerViewIngredients.getLayoutManager().scrollToPosition(mPositionIng);
}
super.onViewStateRestored(savedInstanceState);
}
当方向改变时,我只需要保存滚动位置即可..请帮助.任何建议将为您提供充分的帮助.谢谢...
I just need to save scroll position while the orientation changes .. Please help.Any Suggestion will be help full. Thanks......
推荐答案
让Android OS为您处理该问题,在所需标签活动内的AndroidManifest.xml
中添加:
Let the Android OS handle that for you, in AndroidManifest.xml
inside your wanted tag activity add:
android:configChanges="orientation|screenSize"
这篇关于如何在片段中保存Recyclerview的滚动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!