1

How is it possible to go back to the last Activity one has been in from a Fragment? Let's assume we've Activity A and Fragment A. I launch Fragment A from Activity A, and now I want to go back to Fragment A. When I press on the back button on my phone it closes the app.

I launch the fragment by using the FragmentManager:

Fragment fragment = new Kontakt();
            getFragmentManager().beginTransaction()
                    .add(R.id.kontaktfrag, fragment)
                    .commit();

Is the solution; popBackStackImmediate() or addToBackStack() ?

dada dudu
  • 129
  • 6

2 Answers2

1

Firstly try addToBackStack when adding your fragment. then you need to override your onBackPressed function of your activity, for example:

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

I tried myself and it worked.

linhtruong
  • 441
  • 3
  • 12
0

try adding

 getFragmentManager()
.beginTransaction()
.addToBackStack("")
.commit();

or just add .addToBackStack("") before .commit();

here is the code in your case,

 Fragment fragment = new Kontakt();
        getFragmentManager().beginTransaction()
                .add(R.id.kontaktfrag, fragment)
                .addToBackStack("")
                .commit();
Aziz
  • 1,976
  • 20
  • 23