Reputation: 129
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()
?
Upvotes: 1
Views: 2021
Reputation: 441
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.
Upvotes: 1
Reputation: 2113
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();
Upvotes: 0