pAr
pAr

Reputation: 173

Adding fragments to backStack while moving forward and on clicking back navigating in hierarchy

I am new to Android programming.
I am working on a app in which I use Fragments, and I swap the fragments with

fragmentManager.beginTransaction().replace(R.id.frame_container,fragment)
    .addToBackStack(null).commit();

I want to navigate back by clicking the device back button.
How can I do it?

Upvotes: 0

Views: 170

Answers (2)

Nitin Mali
Nitin Mali

Reputation: 216

Try doing this,I hope this will help

 FragmentManager fm = getSupportFragmentManager();
    String tag = f.getFragmentTag(); // instance method of a to get a tag

    FragmentTransaction ft = fm.beginTransaction();
    ft.replace(R.id.container, f, tag);
    ft.addToBackStack(tag);
    ft.commit();
}
@Override
public void onBackPressed() {
    FragmentManager fm = getSupportFragmentManager();
    if (fm.getBackStackEntryCount() > 0)
    {
        fm.popBackStack();
    } else
    {
        super.onBackPressed();
    }

Upvotes: 1

Samir
Samir

Reputation: 3167

use some id instead of null in addToBackStack method.

Upvotes: 0

Related Questions