How to get current fragment from MainActivity

Mohamed picture Mohamed · Jul 21, 2017 · Viewed 15k times · Source

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?

Answer

AndroidGeek picture AndroidGeek · Jul 22, 2017

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
            }
}