我有一个几乎“单一活动的应用程序”,我尝试将主片段替换为-例如-所选导航项上的配置文件片段,但是我担心这会由于在提交之后提交而导致非法状态异常
onSaveInstanceState
也就是状态损失:https://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html
我用过
commitAllowingStateLoss
避免陷入状态损失崩溃
但可以更改它。
navigationView
.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.main:
Fragment f = getSupportFragmentManager().findFragmentByTag("main");
if (f==null || !f.isVisible()) {
getSupportFragmentManager().beginTransaction().replace(R.id.containerLayout, new MainFragment(), "main").commitAllowingStateLoss();
}
break;
case R.id.myProfile:
Fragment f2 = getSupportFragmentManager().findFragmentByTag("myProfile");
if (f2==null || !f2.isVisible()) {
getSupportFragmentManager().beginTransaction().replace(R.id.containerLayout, new MyProfileFragment(), "myProfile").commitAllowingStateLoss();
}
break;
mDrawerLayout.closeDrawers();
return true;
}
});
您认为这真的会导致状态丢失吗? 如果是这样,我该如何避免?