我有重叠片段的这个问题。我读了其他的决议,但是对于像这样的问题,它们似乎过于复杂。它发生在某个时候app没有被使用然后它被恢复或重新创建时,它似乎记得最后一个片段并创建了新片段,好像上次应用已被销毁一样。
这是与savedInstanceState
相关的吗?
代码:
// used in onCreate()
private void setUpFragments(){
Fragment fragment;
switch (fragmentName){
case CALLS:
fragment = new CallLogsFragment();
break;
case CONTACTS:
fragment = new ContactListFragment();
break;
case SETUP:
fragment = new SetupFragment();
break;
case REGISTER:
fragment = new RegisterFragment();
break;
default:
fragment = new SetupFragment();
}
getFragmentManager().beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.nav_calls:
setFragment(new CallLogsFragment());
break;
case R.id.nav_contacts:
setFragment(new ContactListFragment());
break;
case R.id.nav_add_contacts:
setFragment(new AddContactsFragment());
break;
case R.id.nav_setup:
setFragment(new SetupFragment());
break;
default:
setFragment(new ContactListFragment());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void setFragment(Fragment fragment){
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
答案 0 :(得分:1)
默认情况下,您没有 的 打破; 强>
default:
fragment = new SetupFragment();
比两种情况都要好
default:
fragment = new SetupFragment();
break;
您可以查看我的代码:
在程序的乞讨中(在onCreate中)
getSupportFragmentManager()
.beginTransaction()
.addToBackStack(null)
.add(FRAME_LAYOUT,
createFragment(defaultCurrentItem),
createItemDescription(defaultCurrentItem))
.commit();
开始交易的功能
private Fragment createFragment(int position){
switch (position) {
case BOT_NAV_POSITION_SETTINGS:
return new SettingsFragment_();
case BOT_NAV_POSITION_STATISTICS:
return new StatisticsFragment_();
case BOT_NAV_POSITION_MAIN:
return new MainFragment_();
case BOT_NAV_POSITION_FORTH:
return new ForthFragment_();
case BOT_NAV_POSITION_REMINDERS:
return new ReminderFragment_();
}
throw new IllegalArgumentException();
}
以后需要更改片段时
getSupportFragmentManager()
.beginTransaction()
.replace(FRAME_LAYOUT,
createFragment(position),
createItemDescription(position))
.addToBackStack(null)
.commit();
答案 1 :(得分:1)
你是对的,只有在新创建活动时才设置片段(即调用setupFragments)(即savedInstanceState == null)。
在活动娱乐中,活动的片段管理器将恢复其旧状态。如果未检查savedInstanceState,则新提交的片段和片段管理器的已还原片段将重叠。