How to get current fragment from MainActivity
Solution 1
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
}
}
Solution 2
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);
Solution 3
you can use this to get fragment id for non support fragment
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment_id);
if(fragment!=null)
{
getFragmentManager()
.beginTransaction()
.addToBackStack(null)
.commit();
}
Mohamed
Updated on June 06, 2022Comments
-
Mohamed almost 2 years
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?
-
Mohamed almost 7 yearsQuestion is how can I get current fragment (or its class name) which is active, from main activity.
-
Mohamed almost 7 yearsProblem is I don't use support library, so SupportFragmentManager. Can I use it without using support fragment?
-
zeekhuge almost 7 yearsMain activity is the one that replaces the fragment . isnt it ? so main activity should already know what fragment it is displaying (use one variable, thats it). As for adding to the backtstack, you just need to use
addToBackStack()
before you replace the current fragment with the new one. -
Mohamed almost 7 yearsMenu is not the only place that I replace fragments. It could be changed from inside of fragments. I know about second part.
-
zeekhuge almost 7 yearsEdited the ans.
-
Mohamed almost 7 yearsThanks for suggestion, but as I've said I don't want to keep track of it myself. I'm aware of how it works too. It is stack, and I only want to get the one which is at the top of it, just like .pop()