3

I have 3 fragments Fragment1, Fragment2 and Fragment3 and navigation is like

Fragment1->Fragment2->Fragment3

But on back press From Fragment3 go back to Fragment2 after completing some task like from Fragment2. And from Fragment1 finish this activity.

what will be the best method to do this task.

Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
Vineeth Mohan
  • 2,584
  • 4
  • 17
  • 31
  • Try to create two methods in activity. In one view pager item++ and in second view pager item-- . use this methods in fragment back pressed accordingly. – Vidhi Dave Feb 01 '18 at 12:37
  • some good answers here for what you're after (I think!) https://stackoverflow.com/questions/28930501/back-navigation-with-fragments-toolbar – Saik Caskey Feb 01 '18 at 13:00

3 Answers3

2

Please follow the process. 1. When you add fragment add below code to your code

fragmentTransaction.addToBackStack(null);
  1. Then back button handle from the activity.

    @Override
    public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount()>0){
        getFragmentManager().popBackStack();
    }else {
        super.onBackPressed();
    } }
    

It will be working perfectly. Happy coding.

Shohel Rana
  • 2,332
  • 19
  • 24
2

As per your question just you have to add addToBackStack() method before commit() transaction.

for example:

FirstFragment firstFragment = new FirstFragment();
getSupportFragmentManager().beginTransaction()
    .replace(R.id.article_fragment, firstFragment)
    .addToBackStack(null).commit();

Add second and third fragment same as above manner and just add code in onBackPressed() Override method.

for example:

@Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() > 0) {
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    } 
}
amrro
  • 1,526
  • 17
  • 21
Pratik Satani
  • 1,115
  • 1
  • 9
  • 25
  • Can i check Fragment instance by getSupportFragmentManager().findFragmentBYId(id) inside onBackPress? – Vineeth Mohan Feb 02 '18 at 05:37
  • In fact, you may need to visit this answer of GoodLife on (https://stackoverflow.com/questions/20340303/in-fragment-on-back-button-pressed-activity-is-blank/20340492) – meyasir Jun 20 '18 at 05:58
1

There is no need to handle OnBackPress inside Fragment. When you performing Fragment transaction, you can put your fragment to BackStack:

When there are FragmentTransaction objects on the back stack and the user presses the Back button, the FragmentManager pops the most recent transaction off the back stack and performs the reverse action (such as removing a fragment if the transaction added it).

More details you can get from this article.

Denysole
  • 3,903
  • 1
  • 20
  • 28