我找到了一些代码,用于在屏幕旋转后保存和恢复RecyclerView
的状态,但它不起作用。
代码:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(Constants.LIST_SAVED_POSITION, recyclerView.getLayoutManager().onSaveInstanceState());
}
@Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (savedInstanceState!=null && savedInstanceState.containsKey(Constants.LIST_SAVED_POSITION)){
Parcelable parcelable;
parcelable = savedInstanceState.getParcelable(Constants.LIST_SAVED_POSITION);
recyclerView.getLayoutManager().onRestoreInstanceState(parcelable);
}
}
屏幕旋转后,旧位置不会恢复。我知道我可以保存整数变量,但这种方式似乎更好。
有人能帮我用这种方法解决这个问题吗。
发布于 2016-02-16 09:09:53
我发现了问题。正在对片段调用此代码。但问题是在活动中碎片的再创造。当我修复重新创建片段时,list会在不保存状态的情况下还原该位置。
旧代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_supplication_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
chapter = getIntent().getIntExtra(Constants.SELECTED_ITEM, 1);
fragmentSupplicationDetail = new FragmentSupplicationDetail();
Bundle extras = new Bundle();
extras.putInt(Constants.SELECTED_ITEM, chapter);
fragmentSupplicationDetail.setArguments(extras);
transaction.replace(R.id.container, fragmentSupplicationDetail, SUPPLICATION_FRAGMENT_TAG).commit();
}
修正:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_supplication_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
chapter = getIntent().getIntExtra(Constants.SELECTED_ITEM, 1);
if (getSupportFragmentManager().findFragmentByTag(SUPPLICATION_FRAGMENT_TAG) == null){
fragmentSupplicationDetail = new FragmentSupplicationDetail();
Bundle extras = new Bundle();
extras.putInt(Constants.SELECTED_ITEM, chapter);
fragmentSupplicationDetail.setArguments(extras);
Log.d(Constants.LOG_TAG, getClass().getSimpleName() + ": Создаем фрагмент ");
}else {
fragmentSupplicationDetail = (FragmentSupplicationDetail) getSupportFragmentManager().findFragmentByTag(SUPPLICATION_FRAGMENT_TAG);
Log.d(Constants.LOG_TAG, getClass().getSimpleName() + ": Восстанавливаем фрагмент ");
}
transaction.replace(R.id.container, fragmentSupplicationDetail, SUPPLICATION_FRAGMENT_TAG).commit();
}
发布于 2016-02-16 08:19:58
您可以将其添加到manifist.xml中的活动中,以禁用该活动以重新创建自身,因此在屏幕旋转后,该活动保存所有变量。
android:configChanges="orientation|keyboardHidden"
>
发布于 2016-02-16 08:18:49
我最近正在使用回收器视图,并希望拥有与您想要的相同的功能,我遵循了下面提到的教程,即使在旋转屏幕之后,它也维护了view.Please的状态,请参考下面的链接。
http://www.androidtutorialpoint.com/material-design/listing-items-using-recyclerview/
希望这能帮上忙!
https://stackoverflow.com/questions/35437318
复制