Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current fragment from MainActivity

I've done some research but I really couldn't find the answer.

I have single activity with side menu, and holder. I have many (non support) fragments, and all of them are using same holder (one at a time).

When user uses menu (it's in main activity), and goes another page, I want to add name of the current fragment to backstack (using .addToBackStack(Fragment1.class.getName())), but I couldn't find how to get current fragment.

I don't want to implement interface etc to keep track of current fragment. There is a super simple way using fragmentManger isn't there?

like image 224
Mohamed Avatar asked Sep 19 '25 15:09

Mohamed


2 Answers

You can get your current fragment like this:

if (getFragmentManager().getBackStackEntryCount() > 1) {
            Fragment f = getFragmentManager().findFragmentById(R.id.content_frame);
            if (f instanceof BlankFragment) {
                // Do something
            }
}
like image 174
AndroidGeek Avatar answered Sep 22 '25 06:09

AndroidGeek


OK,

If you want to get latest entry from backstack(thanks to @AndroidGeek);

fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount()-1);

and, if you want to get currently active fragment (thanks to @Salman500 @AndroidGeek);

Fragment f = getFragmentManager().findFragmentById(R.id.fragment_holder);
like image 32
Mohamed Avatar answered Sep 22 '25 07:09

Mohamed