Fragments 通常会在 configuration 更改时重新创建。如果您不希望发生这种情况,请使用
片段构造函数中的setRetainInstance(true);
这将导致在配置更改期间保留片段。
Docs
现在当 Activity 因为方向改变而重新启动时,Android 框架会自动重新创建并添加 Fragment。
如果您想在configuration 更改使用期间删除片段:
在活动中
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
也在清单中:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
现在在 Activity 的 onCreate() 中删除 Fragment 使用:
Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_frame); //your fragment
if(f == null){
//there is no Fragment
}else{
//It's already there remove it
getSupportFragmentManager().beginTransaction().remove(f).commit();
}