Search code examples
androidandroid-fragmentsfragmentmanager

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?


Solution

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