I had created a utility file to replace and add the fragment to backstack, if the fragment is not in backstack otherwise just replace the fragment and the current fragment must not be the same or at the top of stack, This fragment method works well to add the method to backstack if not present in backstack else just simply replace it if not in backstack or just return from the method if the topmost fragment is same.
The issue is when the two fragments is added to the backstack initially signin then signup, and signin is pressed again,and now when i pressed the back button, sigup fragment is popped from backstack but when i again click on signup button, then signup fragment is not in backstack but still the following condition ,
if (myFragment != null && myFragment.isVisible())
{
LogUtil.e( "replaceFragmentBackStack: ",": "+ myFragment.getClass().getSimpleName());
return;
}
get satisfied, so please help me in sorting out this issue
Here is my utility file for replacing fragment,
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();
}
}
Here is the onBackpress event in Activity,
@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();
}
Here is the method to get className,
public static String getClassName(Class classa)
{
/* String c=classa.getSimpleName();
LogUtil.e("ClassName:-",c+"");*/
return classa.getSimpleName();
}