我有一个活动。此活动检查用户是否已登录。如果已登录活动的用户显示LoginFragment。如果用户从LoginFragment登录,则显示MainFragment和MainFragment用户可以转到SettingsFragment。 但是如果我按下SettingsFragment上的后退按钮,它会加载一个空白片段。
我将此方法用于“片段导航”:
public void showFragment(String fragmentName){
Fragment fragment = null;
boolean backstack = true;
if (fragmentName.equals(SysKeys.MAIN_FRAGMENT)){
fragment = new MainFragment();
} else if (fragmentName.equals(SysKeys.LOGIN_FRAGMENT)){
fragment = new LoginFragment();
backstack = false;
} else if (fragmentName.equals(SysKeys.SETTINGS_FRAGMENT)){
fragment = new SettingsFragment();
} else if (fragmentName.equals(SysKeys.CUSTOM_LOGIN_FRAGMENT)){
fragment = new CustomLoginFragment();
}
if (fragment != null){
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left, R.anim.slide_in_from_left, R.anim.slide_out_to_right);
fragmentTransaction.replace(R.id.main_layout, fragment, fragmentName);
if (backstack){
fragmentTransaction.addToBackStack(null);
}
fragmentTransaction.commit();
}
}
我不想反向登录LoginFragment,但我想要其他人。我的代码或逻辑出了什么问题?
更新: 现在它不显示LoginFragment如果我按下MainFragment上的后退按钮,但有时它只是重新加载MainFragment如果我按下后退按钮。 这是代码:
public void showFragment(String fragmentName){
Fragment fragment = null;
boolean backstack = true;
if (fragmentName.equals(SysKeys.MAIN_FRAGMENT)){
fragment = new MainFragment();
backstack = false;
} else if (fragmentName.equals(SysKeys.LOGIN_FRAGMENT)){
fragment = new LoginFragment();
backstack = false;
} else if (fragmentName.equals(SysKeys.SETTINGS_FRAGMENT)){
fragment = new SettingsFragment();
} else if (fragmentName.equals(SysKeys.CUSTOM_LOGIN_FRAGMENT)){
fragment = new CustomLoginFragment();
}
if (fragment != null){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left, R.anim.slide_in_from_left, R.anim.slide_out_to_right);
fragmentTransaction.replace(R.id.main_layout, fragment, fragmentName);
if (backstack){
fragmentTransaction.addToBackStack(null);
}
fragmentTransaction.commit();
}
}
答案 0 :(得分:1)
因为每次显示片段时,您都已弹出上一个后台堆栈。你为什么要那样做?
尝试删除fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
当你创建MainFragment时也设置backstack = false,所以它不会将MainFragment添加到backstack,当你从MainFragment按回来时你将完成活动
希望这会有所帮助。