I have several fragments, all the fragments has entering & exit from left to right. I received a new requirement that several fragments will have different exit transitions while the previous fragment will be static(won`t have transition). Like in the image below:
I started by adding abstract function in my base fragment if it has different transitions:
public abstract boolean hasDifferentTransitions();
after that I modified the function where I am changing the fragments:
public void replaceFragment(int container, Class<?> fragClass, Bundle b,boolean isSplash)
{
BaseFragment bf = null;
try
{
bf = (BaseFragment) fragClass.newInstance();
}
catch (Exception e)
{
e.printStackTrace();
}
String backStateName = bf.getClass().getSimpleName();
FragmentManager manager = getSupportFragmentManager();
//checking if I am on the same fragment
if(_currentFragment!=null)
{
String currentFragmentName = _currentFragment.getClass().getSimpleName();
if(currentFragmentName.equals(backStateName))//not allow same fragment to be twice in backstack one after the other
return;
}
//checking if the "new fragement" is in the backstack if so I will pop out all the fragments till the required one.
BaseFragment backStackFrag = (BaseFragment) manager.findFragmentByTag(backStateName);
if(backStackFrag!=null)
{
_currentFragment = backStackFrag;
for(int fIndex=manager.getBackStackEntryCount()-1;fIndex>=0;fIndex--) {
String currentFragName = manager.getBackStackEntryAt(fIndex).getName();
if (backStateName.equals(currentFragName)) {
break;
}
manager.popBackStack();
}
}
else {//new fragment - set the transitions by the hasDifferentTransitions returned value
_currentFragment = bf;
FragmentTransaction ft = manager.beginTransaction();
if (isSplash) {
ft.setTransition(FragmentTransaction.TRANSIT_NONE);
} else {
if(bf.hasDifferentTransitions())
{
ft.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right,R.anim.enter_from_right,R.anim.exit_to_left);
}
else
{
ft.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right);
}
}
ft.replace(container, bf, bf.getClass().getSimpleName());
ft.addToBackStack(bf.getClass().getSimpleName());
ft.commitAllowingStateLoss();
}
}
Unfortunately it`s not working as needed when I am on the "special fragment" and then open "regular fragment" they both moved from right to left, also sometimes when I am entering to "special fragment" it opens without any transitions