我创建了一个实用程序文件来替换并将片段添加到backstack,如果片段不在backstack中,否则只需替换片段,当前片段不能相同或位于堆栈顶部, 如果不在backstack中,这个片段方法可以很好地将方法添加到backstack中,如果不在backstack中,只需简单地替换它,或者如果最顶层的片段相同则只返回方法。
问题是当两个片段被添加到后台时最初登录然后注册,再次按下signin,现在当我按下后退按钮时,sigup片段从backstack弹出但是当我再次点击注册按钮时,然后注册片段不在backstack中,但仍然是以下条件,
if (myFragment != null && myFragment.isVisible())
{
LogUtil.e( "replaceFragmentBackStack: ",": "+ myFragment.getClass().getSimpleName());
return;
}
得到满意,所以请帮我解决这个问题
这是我的实用程序文件,用于替换片段,
public static void replaceFragmentBackStack(@NonNull final Object context, @IdRes int target, @NonNull Fragment fragment, Bundle bundle) {
FragmentManager fragmentManager=getFragmentManager(context);
Fragment myFragment = fragmentManager.findFragmentByTag(GeneralFunction.getClassName(fragment));
if (myFragment != null && myFragment.isVisible())
{
LogUtil.e( "replaceFragmentBackStack: ",": "+ myFragment.getClass().getSimpleName());
return;
}
else
{
if (bundle != null)
fragment.setArguments(bundle);
FragmentTransaction t = fragmentManager.beginTransaction();
if (myFragment != null && myFragment.getClass().equals(fragment.getClass())) {
t.replace(target, fragment, GeneralFunction.getClassName(fragment)).commit();
LogUtil.e( "fragment replace ",fragment.getClass().getSimpleName());
}
else
t.replace(target, fragment,GeneralFunction.getClassName(fragment)).addToBackStack(GeneralFunction.getClassName(fragment)).commit();
}
}
这是Activity中的onBackpress事件,
@Override
public void onBackPressed() {
FragmentManager manager = getSupportFragmentManager();
int count=manager.getBackStackEntryCount();
if(count>0)
{
FragmentManager.BackStackEntry backEntry=manager.getBackStackEntryAt(manager.getBackStackEntryCount()-1);
String str=backEntry.getName();
Fragment currentFragment=manager.findFragmentByTag(str);
if(null!=currentFragment) {
String className = null;
if (str.equals(GeneralFunction.getClassName(SignIn.class)))
className = getString(R.string.first_signin);
else if (str.equals(GeneralFunction.getClassName(SignUp.class)))
className = getString(R.string.first_signUP);
tvTitle.setText(className);
//manager.popBackStackImmediate(str,FragmentManager.POP_BACK_STACK_INCLUSIVE);
manager.popBackStackImmediate();
}
}else
finish();
}
以下是获取className的方法,
public static String getClassName(Class classa)
{
/* String c=classa.getSimpleName();
LogUtil.e("ClassName:-",c+"");*/
return classa.getSimpleName();
}