我想用循环器视图保存我的片段,以便在屏幕旋转时恢复它。我正在网上寻找指示,我得到:
在我的片段中
private Parcelable recyclerViewState;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
list.getLayoutManager().onRestoreInstanceState(recyclerViewState);
}
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
recyclerViewState = layoutManager.onSaveInstanceState();
}
在我的活动中
//onCreate
if (savedInstanceState != null) {
getSupportFragmentManager().getFragment(savedInstanceState, LIST_USERS_FRAGMENT);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().getFragment(outState, LIST_USERS_FRAGMENT);
}
我正在进行调试,看起来很好,但是当我旋转屏幕时,我得到了空白片段,没有回收者视图。你能帮我调查一下它发生的原因吗?
答案 0 :(得分:0)
Android中的默认行为是在配置更改时销毁所有附加的片段。要绕过片段重新创建,您应该在片段的OnCreate回调中使用setRetainInstance(true)。
答案 1 :(得分:0)
有不同的选项来处理方向变化:
锁定屏幕方向
<activity
android:name="com.example.test.activity.MainActivity"
android:screenOrientation="portrait"/>
防止重新创建活动
<activity
android:name="com.example.test.activity.MainActivity"
android:configChanges="orientation|screenSize|keyboardHidden"/>
保存基本状态
public class MainActivity extends Activity{
private static final String SELECTED_ITEM_POSITION = "ItemPosition";
private int mPosition;
@Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
// Save the state of item position
outState.putInt(SELECTED_ITEM_POSITION, mPosition);
}
@Override
protected void onRestoreInstanceState(final Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Read the state of item position
mPosition = savedInstanceState.gettInt(SELECTED_ITEM_POSITION);
}
}
保存复杂对象
覆盖
onRetainNonConfigurationInstance()
getLastNonConfigurationInstance()
在 API 级别 13 之后,这些方法已被弃用,取而代之的是更多 Fragment 的 setRetainInstance(boolean) 功能,该功能提供了在配置更改期间保留对象的更简洁和模块化的方法。