How do I get the currently displayed fragment?

When you add the fragment in your transaction you should use a tag.

fragTrans.replace(android.R.id.content, myFragment, "MY_FRAGMENT");

...and later if you want to check if the fragment is visible:

MyFragment myFragment = (MyFragment)getSupportFragmentManager().findFragmentByTag("MY_FRAGMENT");
if (myFragment != null && myFragment.isVisible()) {
   // add your code here
}

See also http://developer.android.com/reference/android/app/Fragment.html


I know it's an old post, but was having trouble with it previously too. Found a solution which was to do this in the onBackStackChanged() listening function

  @Override
    public void onBackPressed() {
        super.onBackPressed();

         Fragment f = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
      if(f instanceof CustomFragmentClass) 
        // do something with f
        ((CustomFragmentClass) f).doSomething();

    }

This worked for me as I didn't want to iterate through every fragment I have to find one that is visible. Hope it helps someone else too.


Here is my solution which I find handy for low fragment scenarios

public Fragment getVisibleFragment(){
    FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
    List<Fragment> fragments = fragmentManager.getFragments();
    if(fragments != null){
        for(Fragment fragment : fragments){
            if(fragment != null && fragment.isVisible())
                return fragment;
        }
    }
    return null;
}