Fragment Transition

109 views Asked by At

I am creating a navigation flow in my application where I have three fragment. Here is the complete scenario,

  • Fragment A (Get OTP)
  • Fragment B (Confirm OTP)
  • Fragment C (Change Password)

User navigation will start from Fragment A. User will input username and req to get OTP. We have added Fragment A in XML Layout.

Fragment B added dynamically and addToBackStack("fragmentB") also. So when we click back button popupbackstack works fine.

Verification confirm will take user to Fragment C (Change Password) screen, now if user click on back it should take user to first screen and skip Fragment B. For that If I replace Fragment C with Fragment B, On back press fragment remain there and does not pop back.

Here is the code for Adding and Replace Fragment B and C respectively.

public void addConfirmOtpView(){
    ConfirmOTPFragment confirmOtpFragment = new ConfirmOTPFragment();
    mFragmentTransaction = mFragmentManager.beginTransaction();
    mFragmentTransaction.add(R.id.containerLayout, confirmOtpFragment, confirmOtpFragment.getClass().getSimpleName());
    mFragmentTransaction.addToBackStack(confirmOtpFragment.getClass().getSimpleName());
    mFragmentTransaction.commit();
}

public void replaceResetPasswordFragment() {
    ResetPasswordFragment resetPassword = new ResetPasswordFragment();
    mFragmentTransaction = mFragmentManager.beginTransaction();
    mFragmentTransaction.replace(R.id.containerLayout, resetPassword);
    mFragmentTransaction.commit();
}

Edit:

@Override
public void onBackPressed() {
    if (mFragmentManager != null && mFragmentManager.getBackStackEntryCount() != 0){
        mFragmentManager.popBackStack();
    }else {
        super.onBackPressed();
    }
}
2

There are 2 answers

0
Mustansar Saeed On

Don't add Fragment A in Backstack or when you open Fragment C, clear the backstack, when you will press the back button, Fragment A will be open. Answer picked from https://stackoverflow.com/a/28361585/3027124.

Hope this helps.

0
Shubhankar S On

While maintaining your current code for fragment transactions, change only addition of the Fragment B as follows:

public void addConfirmOtpView(){
    ConfirmOTPFragment confirmOtpFragment = new ConfirmOTPFragment();
    mFragmentTransaction = mFragmentManager.beginTransaction();
    mFragmentTransaction.replace(R.id.containerLayout, confirmOtpFragment, confirmOtpFragment.getClass().getSimpleName());
    mFragmentTransaction.addToBackStack(confirmOtpFragment.getClass().getSimpleName());
    mFragmentTransaction.commit();
}

This is assuming that you have a common container for all your fragments. Let me know what happens.

Hope this helps!