在我的RecyclerView
Adapter
我使用以下方法记住当前所选项目并在屏幕旋转时恢复它:
private final static String SELECTED_ITEM = "MyAdapter.selectedItem";
public void onSaveInstanceState(Bundle outState){
Log.i("onSave","OnSave "+mSelectedItem);
outState.putInt(SELECTED_ITEM, mSelectedItem);
}
public void onRestoreInstanceState(Bundle savedInstanceState){
if(savedInstanceState.containsKey(SELECTED_ITEM)){
Log.i("onRestore","OnRestore " + savedInstanceState.getInt(SELECTED_ITEM));
notifyItemChanged(mSelectedItem);
mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM);
notifyItemChanged(mSelectedItem);
mRecyclerView.getLayoutManager().scrollToPosition(mSelectedItem);
}
}
在我的Fragment
中包含我正在使用的RecyclerView
:
@Override
public void onSaveInstanceState(Bundle outState) {
if(null != mRecyclerView && null != mRecyclerView.getAdapter()){
((MyAdapter)mRecyclerView.getAdapter()).onSaveInstanceState(outState);
}
super.onSaveInstanceState(outState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(null!=savedInstanceState){
if(null != mRecyclerView && null != mRecyclerView.getAdapter()){
((MyAdapter)mRecyclerView.getAdapter()).onRestoreInstanceState(savedInstanceState);
}
}
}
我看到Log
条消息,但Adapter
不记得选择。
答案 0 :(得分:0)
感谢Selvin的code,我很快意识到问题是我在每次屏幕旋转时重新创建Fragment
而新的Fragment
当然没有选择int还原
在您的根onCreate
的{{1}}方法中,检查您是否是第一次创建Activity
:
Activity
然后在@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
mContentLayout = (FrameLayout)findViewById(R.id.main_content_frame);
if(null==savedInstanceState) {
mFragment = new MyFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(mContentLayout.getId(), mPlatformsFragment);
fragmentTransaction.commit();
}
}
中,要保存所选项目,请使用:
Fragment