How to know which Fragment is being displayed

Asked

Viewed 920 times

1

My app has an Activity that controls the inclusion of Fragments.

Follows:

public static void adicionarFragment(Activity activity, Fragment fragment){
        FragmentManager fragMgr = activity.getFragmentManager();
        FragmentTransaction fragTrans = fragMgr.beginTransaction();

        fragTrans.replace(android.R.id.content, fragment);
        fragTrans.addToBackStack(null);
        fragTrans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        fragTrans.commit();
    }

I wonder if it is possible to find out which Fragment is being displayed ?

Is there any way to use FragmentManager?

Ps: I tried to in this way, but he does not return to me the instance of Fragment

2 answers

1


At the time of replace, vc should set a TAG to your Fragment, example:

fragTrans.replace(android.R.id. content, fragment, "TAG_DO_FRAGMENT");

Then to check which Fragment is being displayed, do it this way:

 NomeDoFragment nomeFragment = (NomeDoFragment)getFragmentManager().findFragmentByTag("TAG_DO_FRAGMENT");
 if (nomeFragment != null && nomeFragment.isVisible()) {

   // se entrar aqui ele está visível

 }

1

You can use the method getFragments() of Fragmentmanager to get a list of all the Ragments added to it.

List<Fragment> fragments = fragMgr.getFragments();

It’s not completely clear in your code but since you use replace(), it seems to me that in your case there will only be one fragment added.
So, the returned list will only have one item and that’s what you’re looking for.

Fragment visibleFragment = fragments.get(0);

To distinguish one Fragment from another, by doing the replace, use a String/Tag:

fragTrans.replace(android.R.id.content, fragment, "Tag1");

Then you can do something like this:

Fragment visibleFragment = fragments.get(0);
switch (visibleFragment.getTag()){
    case "Tag1":
        ...
        break;
    case "Tag2":
        ...
        break;
    ...
   }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.