Home > Mobile >  How to know which Fragment is currently running when using a single activity and multiple fragments
How to know which Fragment is currently running when using a single activity and multiple fragments

Time:04-09

I use a singe activity and embed multiple fragments into it. Now I would like to know within the single activity class, which Fragment is currently being displayed. How can I do this? I had a look at the solution from here How to know if a Fragment is Visible?

MyFragmentClass test = (MyFragmentClass) getSupportFragmentManager().findFragmentByTag("testID");
if (test != null && test.isVisible()) {
     //DO STUFF
}
else {
    //Whatever
}

But I don't know what to you for the parameter "testID". Further, I tried to implement the solution from Get the current fragment object

Fragment currentFragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);

But here I get the error message: "Cannot resolve symbol 'fragment_container'"

Does anyone have an idea how to get the name of the current Fragment that is being displayed when using a single activity and multiple fragments approach?

CodePudding user response:

You can do something like this:

  1. Create a field of Fragment in your activity. Like this:
private Fragment mCurrentlyDisplayingFragment;
  1. Whenever changing the fragment, just pass that fragment object to that. Like this:
MyFragment fragment = new MyFragment();
// show it in the frame layout
mCurrentlyDisplayingFragment = fragment;

Now, whenever you are checking, just check this field. Done

Happy coding

  • Related