How to know which Fragment is being displayed

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's possible to find out which Fragment is being displayed?

Is there any way to unmask using FragmentManager ?

Ps: I've tried this way , but it does not return me the instance of Fragment

    
asked by anonymous 01.09.2017 / 20:25

2 answers

1

At the time of replace, you should set a TAG for your Fragment, eg

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

Then to check which Fragment is displaying, do so:

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

   // se entrar aqui ele está visível

 }
    
01.09.2017 / 20:31
1

You can use getFragments () from FragmentManager for a list of all the fragments added to it.

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

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

Fragment visibleFragment = fragments.get(0);

To distinguish one Fragment from another, when doing 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;
    ...
   }
    
01.09.2017 / 22:15