Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last fragment in back stack

I have seen this post but the solutions posted here are not working for me: get the latest fragment in backstack

When I replace a fragment for another I use:

FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction ft = manager.beginTransaction();

    ft.replace(android.R.id.tabcontent, fragment, tag);
    ft.addToBackStack(null);

    ft.commit();

So, please notice that I'm using tags to detect any fragment.

My problem in particular is the following:

Suppose I have fragment_A, fragment_B and fragment_C. I can get to fragment_C from fragment_A or fragment_B and depending of the parent of call I have to do something particular. So, again I need to recover the last FRAGMENT in the back stack.

When I try to do:

FragmentManager fm = getSupportFragmentManager();

        for(int entry = 0; entry < fm.getBackStackEntryCount(); entry++){
            String ide = fm.getBackStackEntryAt(entry).getName();
           Log.i("TAG", "Found fragment: " + ide);
        }

I get nulls. If I use getId() instead, I get numbers so I tried doing:

int id = fm.getBackStackEntryAt(entry).getId();
Fragment fragment = fm.findFragmentById(id);
Log.i("TAG", "Found fragment: " + fragment.getTag());

But I get nulls.. I dont know what else to do, so any help will be appreciated.

Edit: I call this methods in onBackPressed() { ...}

like image 616
kiduxa Avatar asked Jul 10 '13 03:07

kiduxa


People also ask

What is Addtobackstack null?

This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack. Parameters name An optional name for this back stack state, or null.

What is back stack in fragment?

The user can later reverse the transaction and bring back the previous fragment by pressing the Back button. If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped.


1 Answers

If you're using BackStackEntry.getName(), it should be:

ft.replace(android.R.id.tabcontent, fragment, tag);
ft.addToBackStack(tag);
like image 134
Paul Burke Avatar answered Nov 15 '22 18:11

Paul Burke