How to get the current visible fragment in android?

19,006

Solution 1

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

Usage

if (getVisibleFragment() instanceof HomeScreen) {
  // Logic here...
}

Were MainActivity is the holder and HomeScreen is your one of the fragment.

Solution 2

Fragment getCurrentFragment()
{
    Fragment currentFragment = getSupportFragmentManager()
            .findFragmentById(R.id.content_frame);
    return currentFragment;
}

calling function like this

Fragment visibleFragment=getCurrentFragment();

calling this function you can get current visible fragment.if Any confusion then feel for free to ask thankx :)

Solution 3

android.support.v4.app.Fragment getCurrentFragment()
{
    Fragment currentFragment = getActivity().getSupportFragmentManager()
            .findFragmentById(R.id.frameLayout);
    return currentFragment;
}
Share:
19,006
Saravanan Selvam
Author by

Saravanan Selvam

Updated on June 29, 2022

Comments

  • Saravanan Selvam
    Saravanan Selvam almost 2 years

    I have MainActivity and inside this activity i have four fragments. The fragment name are A,B,C,D.

    Fragment currentVisibleFragment = getSupportFragmentManager().findFragmentByTag(null);
    

    using this above line i am trying to get the current visible fragment but i cant get the current visible fragment.

  • Anil Ugale
    Anil Ugale over 6 years
    R.id.content_frame is view which added fragment in to activity ?
  • BDL
    BDL about 5 years
    Although this code might (or might not) solve the problem, a good answer should always explain what the code does and how it helps.