How do I get the currently displayed fragment?

AndroidAndroid LayoutAndroid IntentAndroid Fragments

Android Problem Overview


I am playing with fragments in Android.

I know I can change a fragment by using the following code:

FragmentManager fragMgr = getSupportFragmentManager();
FragmentTransaction fragTrans = fragMgr.beginTransaction();

MyFragment myFragment = new MyFragment(); //my custom fragment

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

My question is, in a Java file, how can I get the currently displayed Fragment instance?

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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.

Solution 3 - Android

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;
}

Solution 4 - Android

Every time when you show fragment you must put it tag into backstack:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK);		
ft.add(R.id.primaryLayout, fragment, tag);
ft.addToBackStack(tag);
ft.commit();		

And then when you need to get current fragment you may use this method:

public BaseFragment getActiveFragment() {
	if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
		return null;
	}
	String tag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1).getName();
	return (BaseFragment) getSupportFragmentManager().findFragmentByTag(tag);
}

Solution 5 - Android

Kotlin way;

val currentFragment = supportFragmentManager.fragments.last()

Solution 6 - Android

What I am using to find current displaying fragment is in below code. It is simple and it works for me by now. It runs in the activity which holds the fragments

    FragmentManager fragManager = this.getSupportFragmentManager();
    int count = this.getSupportFragmentManager().getBackStackEntryCount();
    Fragment frag = fragManager.getFragments().get(count>0?count-1:count);

Solution 7 - Android

The reactive way:

Observable.from(getSupportFragmentManager().getFragments())
    .filter(fragment -> fragment.isVisible())
    .subscribe(fragment1 -> {
        // Do something with it
    }, throwable1 -> {
        // 
    });

Solution 8 - Android

My method is based on try / catch like this :

MyFragment viewer = null;
    if(getFragmentManager().findFragmentByTag(MY_TAG_FRAGMENT) instanceOf MyFragment){
    viewer = (MyFragment) getFragmentManager().findFragmentByTag(MY_TAG_FRAGMENT);
}

But there may be a better way ...

Solution 9 - Android

Well, this question got lots of views and attention but still did not contained the easiest solution from my end - to use getFragments().

            List fragments = getSupportFragmentManager().getFragments();
            mCurrentFragment = fragments.get(fragments.size() - 1);

Solution 10 - Android

If you are using the AndroidX Navigation:

val currentFragment = findNavController(R.id.your_navhost)?.currentDestination

For more info on this navigation component: https://developer.android.com/guide/navigation/navigation-getting-started

Solution 11 - Android

You can query which fragment is loaded into your Activities content frame, and retrieve the fragment class, or fragment 'simple name' (as a string).

public String getCurrentFragment(){
     return activity.getSupportFragmentManager().findFragmentById(R.id.content_frame).getClass().getSimpleName();
}

Usage:

Log.d(TAG, getCurrentFragment());

Outputs:

D/MainActivity: FragOne

Solution 12 - Android

It's a bit late, But for anyone who is interested : If you know the index of the your desired fragment in FragmentManager just get a reference to it and check for isMenuVisible() function! here :

getSupportFragmentManager().getFragments().get(0).isMenuVisible()

If true Its visible to user and so on!

Solution 13 - Android

ft.replace(R.id.content_frame, fragment, **tag**).commit();
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment currentFragment = fragmentManager.findFragmentById(R.id.content_frame);

3)

if (currentFragment.getTag().equals(**"Fragment_Main"**))
{
 //Do something
}
else
if (currentFragment.getTag().equals(**"Fragment_DM"**))
{
//Do something
}

Solution 14 - Android

If get here and you are using Kotlin:

var fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)

R.id.fragment_container is the id where the fragment is presenting on their activity

Or if you want a nicer solution:

supportFragmentManager.findFragmentById(R.id.content_main)?.let {
    // the fragment exists

    if (it is FooFragment) {
        // The presented fragment is FooFragment type
    }
}

Solution 15 - Android

There's a method called findFragmentById() in SupportFragmentManager. I use it in the activity container like :

public Fragment currentFragment(){
    return getSupportFragmentManager().findFragmentById(R.id.activity_newsfeed_frame);
}

That's how to get your current Fragment. If you have custom Fragment and need to check what Fragment it is, I normally use instanceof :

if (currentFragment() instanceof MyFrag){
    // Do something here
}

Solution 16 - Android

This should work -

val visibleFragment = supportFragmentManager.fragments.findLast { fgm -> fgm.isVisible }
Timber.d("backStackIterator: visibleFragment: $visibleFragment")

Solution 17 - Android

Inspired by Tainy's answer, here is my two cents. Little modified from most other implementations.

private Fragment getCurrentFragment() {
	FragmentManager fragmentManager = myActivity.getSupportFragmentManager();
	int stackCount = fragmentManager.getBackStackEntryCount();
	if( fragmentManager.getFragments() != null ) return fragmentManager.getFragments().get( stackCount > 0 ? stackCount-1 : stackCount );
	else return null;
}

Replace "myActivity" with "this" if it is your current activity or use reference to your activity.

Solution 18 - Android

This is simple way to get current fragment..

getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
  @Override public void onBackStackChanged() {
    currentFragment = fragmentManager.findFragmentById(R.id.content);
    if (currentFragment !=  null && (currentFragment instanceof LoginScreenFragment)) {
      logout.setVisibility(View.GONE);
    } else {
      logout.setVisibility(View.VISIBLE);
    }
  }
});

Solution 19 - Android

Checkout this solution. It worked for me to get the current Fragment.

if(getSupportFragmentManager().getBackStackEntryCount() > 0){
        android.support.v4.app.Fragment f = 
         getSupportFragmentManager().findFragmentById(R.id.fragment_container);
        if(f instanceof ProfileFragment){
            Log.d(TAG, "Profile Fragment");
        }else if(f instanceof SavedLocationsFragment){
            Log.d(TAG, "SavedLocations Fragment");
        }else if(f instanceof AddLocationFragment){
            Log.d(TAG, "Add Locations Fragment");
        }

Solution 20 - Android

it's so simple, not that much code you need to write yourFragment.isAdded() or yourFragment.isVisible();

I prefer isAdded(),both of them return boolean value use it in if condition and must initialize your fragment in onCreate() otherwise you will get null point exception.

Solution 21 - Android

Sev's answer works for when you hit the back button or otherwise change the backstack.

I did something slightly different, though. I have a backstack change listener setup on a base Fragment and its derived fragments and this code is in the listener:

Fragment f = getActivity().getSupportFragmentManager().findFragmentById(R.id.container);

if (f.getClass().equals(getClass())) {
    // On back button, or popBackStack(),
    // the fragment that's becoming visible executes here,
    // but not the one being popped, or others on the back stack

    // So, for my case, I can change action bar bg color per fragment
}

Solution 22 - Android

Easy way to do that :

Fragment fr=getSupportFragmentManager().findFragmentById(R.id.fragment_container);
String fragmentName = fr.getClass().getSimpleName();

Solution 23 - Android

final FragmentManager fm=this.getSupportFragmentManager();
final Fragment fragment=fm.findFragmentByTag("MY_FRAGMENT");

if(fragment != null && fragment.isVisible()){
      Log.i("TAG","my fragment is visible");
}
else{
      Log.i("TAG","my fragment is not visible");
}

Solution 24 - Android

If you are getting the current instance of Fragment from the parent activity you can just

findFragmentByID(R.id.container);

This actually get's the current instance of fragment that's populated on the view. I had the same issue. I had to load the same fragment twice keeping one on backstack.

The following method doesn't work. It just gets a Fragment that has the tag. Don't waste your time on this method. I am sure it has it's uses but to get the most recent version of the same Fragment is not one of them.

findFragmentByTag()

Solution 25 - Android

None of the above 30 answers fully worked for me. But here is the answer that worked:

Using Kotlin, when using Navigation Component:

fun currentVisibleFragment(): Fragment? {
    return supportFragmentManager.fragments.first()?.getChildFragmentManager()?.getFragments()?.get(0)
}

Solution 26 - Android

Kotlin safer way than exposed here

supportFragmentManager.fragments.lastOrNull()?.let { currentFragment ->
               
      //Do something here
 }

Solution 27 - Android

This is work for me. I hope this will hepl someone.

FragmentManager fragmentManager = this.getSupportFragmentManager();	 
        String tag = fragmentManager
    				.getBackStackEntryAt(
    				fragmentManager
    				.getBackStackEntryCount() - 1)
    			    .getName();
              Log.d("This is your Top Fragment name: ", ""+tag);

Solution 28 - Android

I found findFragmentByTag isn't that convenient. If you have String currentFragmentTag in your Activity or parent Fragment, you need to save it in onSaveInstanceState and restore it in onCreate. Even if you do so, when the Activity recreated, onAttachFragment will called before onCreate, so you can't use currentFragmentTag in onAttachFragment(eg. update some views based on currentFragmentTag), because it's might not yet restored.

I use the following code:

Fragment getCurrentFragment() {
    List<Fragment> fragments = getSupportFragmentManager().getFragments();
    if(fragments.isEmpty()) {
        return null;
    }
    return fragments.get(fragments.size()-1);
}

The document of FragmentManager state that

> The order of the fragments in the list is the order in which they were added or attached.

When you need to do stuff based on current fragment type, just use getCurrentFragment() instance of MyFragment instead of currentFragmentTag.equals("my_fragment_tag").

Note that getCurrentFragment() in onAttachFragment will not get the attaching Fragment, but the previous attached one.

Solution 29 - Android

getSupportFragmentManager().findFragmentById(R.id.content_frame).getClass().getSimpleName();

Well, I guess this is the most straight forward answer to this question. I hope this helps.

Solution 30 - Android

You can do it very easily also with a URL in logcat which will redirect you to the source code of current fragment source code. First, you need to add an OnBackStackChangedListener in host activity like -

activity.getChildFragmentManager().addOnBackStackChangedListener(backStackListener);

And the OnBackStackChangedListener implementation is -

    public FragmentManager.OnBackStackChangedListener backStackListener = () -> {

    String simpleName = "";
    String stackName = getStackTopName().trim();

    if (Validator.isValid(stackName) && stackName.length() > 0) {

      simpleName = stackName.substring(Objects.requireNonNull(stackName).lastIndexOf('.') + 1).trim();

      List<Fragment >
       fragmentList = getChildFragmentManager().getFragments();
      Fragment myCurrentFragment;

      for (int i = 0; i < fragmentList.size(); i++) {
       myCurrentFragment= fragmentList.get(i);
       if (myCurrentFragment.getClass().getSimpleName().equals(simpleName)) {
        //Now you get the current displaying fragment assigned in myCurrentFragment.
        break;
       }
       myFragment = null;
      }
     }


     //The code below is for the source code redirectable logcat which would be optional for you.
     StackTraceElement stackTraceElement = new StackTraceElement(simpleName, "", simpleName + ".java", 50);
     String fileName = stackTraceElement.getFileName();
     if (fileName == null) fileName = "";
     final String info = "Current Fragment is:" + "(" + fileName + ":" +
     stackTraceElement.getLineNumber() + ")";
     Log.d("now", info + "\n\n");
    };

And the getStackTopName() method is -

public String getStackTopName() {
    FragmentManager.BackStackEntry backEntry = null;
    FragmentManager fragmentManager = getChildFragmentManager();
    if (fragmentManager != null) {
        if (getChildFragmentManager().getBackStackEntryCount() > 0)
            backEntry = getChildFragmentManager().getBackStackEntryAt(
                    getChildFragmentManager().getBackStackEntryCount() - 1
            );
    }
    return backEntry != null ? backEntry.getName() : null;
}

Solution 31 - Android

  SupportFragmentManager.BeginTransaction().Replace(Resource.Id.patientFrameHome, test, "Test").CommitAllowingStateLoss();  

var fragment = SupportFragmentManager.FindFragmentByTag("Test") as V4Fragment;

  if (fragment == null && fragment.IsVisiable is true)
{
}

Solution 32 - Android

I had to do this very recently

public Fragment getCurrentFragment() {
     return fragmentManager.findFragmentById(R.id.container);
}

and finaly i got last fragment on this container.

Solution 33 - Android

In the main activity, the onAttachFragment(Fragment fragment) method is called when a new fragment is attached to the activity. In this method, you can get the instance of the current fragment. However, the onAttachFragment(Fragment fragment) method is not called when a fragment is popped off the back stack, ie, when the back button is pressed to get the top fragment on top of the stack. I am still looking for a callback method that is triggered in the main activity when a fragment becomes visible inside the activity.

Solution 34 - Android

In case of scrolled fragments, when your use instance of ViewPager class, suppose mVeiwPager, you can call mViewPager.getCurrentItem() for get current fragment int number.

in MainLayout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical"
    tools:context="unidesign.photo360.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="false"
        android:theme="@style/AppTheme.AppBarOverlay"
        app:expanded="false">

        <android.support.v7.widget.Toolbar
            android:id="@+id/main_activity_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:title="@string/app_name">

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>


    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.support.v4.view.ViewPager>
    
</android.support.design.widget.CoordinatorLayout>

in MainActivity.kt

class MainActivity : AppCompatActivity() {
    
        lateinit var mViewPager: ViewPager
        lateinit var pageAdapter: PageAdapter
        
//      ...
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            
            pageAdapter = PageAdapter(supportFragmentManager)
            mViewPager = findViewById(R.id.view_pager)
//          ...
            }
            
        override fun onResume() {
          super.onResume()
          var currentFragment = pageAdapter.getItem(mViewPager.currentItem)
//         ...
          }

Solution 35 - Android

I had to do this very recently and none of the answers here really suited this scenario.

If you are confident that only one fragment will be visible (full-screen), so really want to find what's at the top of the backstack. For instance, as a Kotlin for Fragment:

import androidx.fragment.app.Fragment

fun Fragment.setVisibilityChangeListener(clazz: Class<out Fragment>, listener: (Boolean) -> Unit) {
    fragmentManager?.run {
        addOnBackStackChangedListener {
            val topFragmentTag = getBackStackEntryAt(backStackEntryCount - 1).name
            val topFragment = findFragmentByTag(topFragmentTag)
            listener(topFragment != null && topFragment::class.java == clazz)
        }
    }
}

And use it like:

class MyFragment: Fragment {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setVisibilityChangeListener(this::class.java) { visible -> 
            // Do stuff
        }
    }
}

Solution 36 - Android

Here is a Kotlin solution:

if ( this.getSupportFragmentManager().getBackStackEntryCount()>0 ) {
    var fgmt = this.getSupportFragmentManager().fragments[this.getSupportFragmentManager().getBackStackEntryCount()-1]
    if( fgmt is FgmtClassName ) {
        (fgmt as FgmtClassName).doSth()
    }
}

Simplified way:

with ( this.getSupportFragmentManager() ) {
    if ( getBackStackEntryCount()>0 ) {
        var fgmt = fragments[getBackStackEntryCount()-1]
        if ( fgmt is FgmtClassName ) {
            (fgmt as FgmtClassName).doSth()
        }
    }
}

        

Solution 37 - Android

If you are using Jetpack Navigation library:

val currentFragment = defaultNavigator.currentDestination

Solution 38 - Android

If you use the Support library v13 than this issue is fixed and you should simply override:

@Override
public void setUserVisibleHint(boolean isVisibleToUser)
{
	// TODO Auto-generated method stub
	super.setUserVisibleHint(isVisibleToUser);
}

The thing is, you can't mix the two because the fragment is not compatible with the Fragment Class of the of the version 4.

If you are not and you are using the V4 support lib, Override the setPrimaryItem method to your FragmentStatePagerAdapter.

I was using this to update the Actionbat title in big lists.

Solution 39 - Android

Maybe the simplest way is:

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

It worked for me

Solution 40 - Android

Using an event bus (like Otto, EventBus or an RxJava Bus) is especially handy in these situations.

While this approach doesn't necessarily hand you down the currently visible fragment as an object (though that too can be done but it leads to a longer call chain), it allows you execute actions on the currently visible fragment (which is usually what you want to do knowing the currently visible fragment).

  1. make sure you respect the fragment lifecycle and register/unregister the event bus at the appropriate times
  2. at the point where you need to know the currently visible fragment and execute a set of actions. shoot an event out with the event bus.

all visible fragments that have registered with the bus will execute the necessary action.

Solution 41 - Android

I ran into a similar problem, where I wanted to know what fragment was last displayed when the back key was pressed. I used a very simple solution that worked for me. Each time I open a fragment, in the onCreate() method, I set a variable in my singleton (replace "myFragment" with the name of your fragment)

MySingleton.currentFragment = myFragment.class;

The variable is declared in the singleton as

public static Class currentFragment = null; 

Then in the onBackPressed() I check

    if (MySingleton.currentFragment == myFragment.class){
        // do something
        return;
    }
    super.onBackPressed();

Make sure to call the super.onBackPressed(); after the "return", otherwise the app will process the back key, which in my case caused the app to terminate.

Solution 42 - Android

A bit strange but I looked at FragmentManager$FragmentManagerImpl and the following works for me:

public static Fragment getActiveFragment(Activity activity, int index)
{
    Bundle bundle = new Bundle();
    String key = "i";
    bundle.putInt(key,index);
    Fragment fragment=null;
    try
    {
        fragment = activity.getFragmentManager().getFragment(bundle, key);
    } catch(Exception e){}
    return fragment;
}

to get the first active fragment use 0 as the index

Solution 43 - Android

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

This works for me. You need to perform a null check before you iterate through the fragments list. There could be a scenario that no fragments are loaded on the stack.

The returning fragment can be compared with the fragment you want to put on the stack.

Solution 44 - Android

Please try this method .....

private Fragment getCurrentFragment(){
    FragmentManager fragmentManager = getSupportFragmentManager();
    String fragmentTag = fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount() - 1).getName();
    Fragment currentFragment = getSupportFragmentManager()
.findFragmentByTag(fragmentTag);
    return currentFragment;
}

Solution 45 - Android

You can get current fragment by using following code

FragmentClass f = (FragmentClass)viewPager.getAdapter().instantiateItem(viewPager, viewPager.getCurrentItem());

Solution 46 - Android

You can add a class variable selectedFragment, and every time you change the fragment you update the variable.

public Fragment selectedFragment;
public void changeFragment(Fragment newFragment){
    FragmentManager fragMgr = getSupportFragmentManager();
    FragmentTransaction fragTrans = fragMgr.beginTransaction();
    fragTrans.replace(android.R.id.content, newFragment);
    fragTrans.addToBackStack(null);
    fragTrans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    fragTrans.commit();
    //here you update the variable
    selectedFragment = newFragment;
}

then you can use selectedFragment wherever you want

Solution 47 - Android

Hello I know this is an very old issue, but I would like to share my own solution..

In order to get the browsed fragment list by the user, I created a helper class:

public class MyHelperClass{

    private static ArrayList<Fragment> listFragment = new ArrayList<>();

    public static void addFragment(Fragment f){
        if(!existFragment(f)) {
            listFragment.add(f);
        }
    }
    public static void removeFragment(){
        if(listFragment.size()>0)
            listFragment.remove(listFragment.size()-1);
    }
    public static Fragment getCurrentFragment(){
        return listFragment.get(listFragment.size()-1);
    }
    public static int sizeFragments(){
        return listFragment.size();
    }
    private static Boolean existFragment(Fragment f){
        Boolean ret = false;
        for(Fragment fragment : listFragment){
            if (fragment.getClass() == f.getClass()){
                ret = true;
            }
        }
        return ret;
    }

And into the main Activity, I override onAttachFragment method

@Override
public void onAttachFragment(Fragment f) {
    super.onAttachFragment(f);

    MyHelperClass.addFragment(f);
}

and also, I override onBackPressed Method:

@Override
public void onBackPressed() {
        General.removeFragment();
        if(General.sizeFragments()>0){
            Fragment fragment = null;
            Class fragmentClass = General.getCurrentFragment().getClass();

            try {
                fragment = (Fragment) fragmentClass.newInstance();
                fragment.setArguments(General.getCurrentFragment().getArguments());
            } catch (Exception e) {
                e.printStackTrace();
            }

            fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
        }else{
            super.onBackPressed();
        }
}

so by this way you any time can get the active fragment with MyHelperClass.getCurrentFragment()

I hope this be helpful for anyone

regards

Solution 48 - Android

well i think you want to see in which fragment u're in i guess there is a sollution i dont think its the best but it works First at all


you should create your parent fragment that it extends Fragment


public class Fragment2 extends Fragment {
    private static position;
    public static int getPosition() {
        return position;
    }

    public static void setPosition(int position) {
        FragmentSecondParent.position = position;
    }
}

Second

you should extend it in every fragment and in each write in onCreateView

setPosition(//your fragmentposition here)

Third


where you want to get the current fragment you should


write this

Fragment2 fragment= (Fragment2) getSupportFragmentManager()
    .findFragmentById(R.id.fragment_status);

int position = fragment.getPosition();
if(//position condition)
{
    //your code here
}

Solution 49 - Android

this is the best way:

       android.app.Fragment currentFragment=getFragmentManager().findFragmentById(R.id.main_container);
            if(currentFragment!=null)
            {
                String[] currentFragmentName = currentFragment.toString().split("\\{");
                if (currentFragmentName[0].toString().equalsIgnoreCase("HomeSubjectFragment"))
                {
                    fragment = new HomeStagesFragment();
                    tx = getSupportFragmentManager().beginTransaction();
                    tx.replace(R.id.main_container, fragment);
                    tx.addToBackStack(null);
                    tx.commit();
                }
                else if(currentFragmentName[0].toString().equalsIgnoreCase("HomeStagesFragment"))
                {
                    new AlertDialog.Builder(this)
                            .setMessage("Are you sure you want to exit?")
                            .setCancelable(false)
                            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    finish();
                                }
                            })
                            .setNegativeButton("No", null)
                            .show();
                }

            }

dont forget to define this in header :

private Fragment fragment;
FragmentTransaction tx;

Solution 50 - Android

I also stuck on this point. What I finally did, just declared an array of Fragments:

private static PlaceholderFragment[] arrFrg;

(in my case it is PlaceholderFragment) and packed all thsess Fragemnts into this array without tagging :)

        public static PlaceholderFragment newInstance(int sectionNumber) {
            final PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            arrFrg[sectionNumber] = fragment;

            return fragment;
}

Then you can easily access the currently displayed Fragment:

arrFrg[mViewPager.getCurrentItem()];

I understand, this is probably not the best solution but it perfectly works for me :)

Solution 51 - Android

In case you have nested fragments, like viewpagers inside viewpagers etc and you want to get all nested fragments.

Thanks and courtesy of Matt Mombrea answer a little tweaked version.

private List<Fragment> getVisibleFragments(List<Fragment> searchFragments, List<Fragment> visibleFragments) {
    if (searchFragments != null && searchFragments.size() > 0) {
        for (Fragment fragment : searchFragments) {
            List<Fragment> nestedFragments = new ArrayList<>();
            List<Fragment> childFMFragments = fragment.getChildFragmentManager().getFragments();
            List<Fragment> fmFragments = fragment.getFragmentManager().getFragments();
            fmFragments.retainAll(childFMFragments);
            nestedFragments.addAll(childFMFragments);
            nestedFragments.addAll(fmFragments);
            getVisibleFragments(nestedFragments, visibleFragments);
            if (fragment != null && fragment.isVisible()) {
                visibleFragments.add(fragment);
            }
        }
    }
    return visibleFragments;
}

And here is the usage:

List<Fragment> allVisibleFragments = getVisibleFragments(searchFragments, visibleFragments);

For example:

List<Fragment> visibleFragments = new ArrayList<>();
List<Fragment> searchFragments = MainActivity.this.getSupportFragmentManager().getFragments();
Toast.makeText(this, ""+getVisibleFragments(searchFragments, visibleFragments), Toast.LENGTH_LONG).show();

Solution 52 - Android

if getFragmentManager() not works then try with getSupportFragmentManager() and add a tag at the time of load fragment.

public void onBackPressed(){

    Fragment fragment=getSupportFragmentManager().findFragmentByTag(/*enter your tag*/);


    if(fragment!=null && fragment.isVisible())
    {
        //do your code here
    }
    else
    {
       //do your code here
    }

}

Solution 53 - Android

In Your Activity init your fragment before on create

    MyFragment myFragment = new MyFragment(); // add this
 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
........

then call the method to view your fragment

openFragment(this.myFragment);

Here is the method

> (R.id.frame_container) is your fragment container id in xml file > (Frame Layout)

 private void openFragment(final Fragment fragment)   {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.frame_container, fragment);
        transaction.commit();

    }

then in your activity, the Override method should be like

    public void onBackPressed() {
            if (myFragment.isVisible()) {
                myFragment.onBackPressed(this);
                return;
            }
            super.onBackPressed();
        }

then inside your fragment put this method

public  void onBackPressed(Activity activity) {
    Toast.makeText(activity, "Back Pressed inside Fragment", Toast.LENGTH_SHORT).show();
}

Solution 54 - Android

Return the currently active primary navigation fragment for this FragmentManager.

public @Nullable Fragment getPrimaryNavigationFragment()      
Fragment fragment = fragmentManager.getPrimaryNavigationFragment();  
    

Solution 55 - Android

I just needed to do this, if you have access to the nav controller, you can obtain the current fragment from the back stack easily:

// current fragments label/title:
navController.backStack.last.destination.label

// current fragments name:
navController.backStack.last.destination.displayName

To get access to nav controller (replace with correct name):

val navController = findNavController(R.id.nav_host_fragment_activity_main)

Solution 56 - Android

In androidx.fragment:fragment-ktx:1.4 there is a new way how can we get recently added fragment to the container. If you using FragmentContainerView as a container for yours fragments it will be easy:

val fragmentContainer: FragmentContainerView = ...
val currentFragment: Fragment = fragmentContainer.getFragment()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeem.finView Question on Stackoverflow
Solution 1 - AndroidramdroidView Answer on Stackoverflow
Solution 2 - AndroidSevView Answer on Stackoverflow
Solution 3 - AndroidMatt MombreaView Answer on Stackoverflow
Solution 4 - AndroidDmitry_LView Answer on Stackoverflow
Solution 5 - AndroidCafer Mert CeyhanView Answer on Stackoverflow
Solution 6 - AndroidtainyView Answer on Stackoverflow
Solution 7 - AndroidlocalhostView Answer on Stackoverflow
Solution 8 - AndroidThordaxView Answer on Stackoverflow
Solution 9 - AndroidNativView Answer on Stackoverflow
Solution 10 - AndroidCory RoyView Answer on Stackoverflow
Solution 11 - AndroidMr LView Answer on Stackoverflow
Solution 12 - AndroidMohammadRezaView Answer on Stackoverflow
Solution 13 - AndroidNam Ngo ThanhView Answer on Stackoverflow
Solution 14 - AndroidpableirosView Answer on Stackoverflow
Solution 15 - AndroidKevin MurvieView Answer on Stackoverflow
Solution 16 - AndroidAnoop M MaddasseriView Answer on Stackoverflow
Solution 17 - AndroidEMalikView Answer on Stackoverflow
Solution 18 - Androidlallu SukendhView Answer on Stackoverflow
Solution 19 - AndroidHaroon khanView Answer on Stackoverflow
Solution 20 - AndroidSaddanView Answer on Stackoverflow
Solution 21 - AndroidMCLLCView Answer on Stackoverflow
Solution 22 - AndroidBiplob DasView Answer on Stackoverflow
Solution 23 - AndroidkmarinView Answer on Stackoverflow
Solution 24 - AndroidYasin YaqoobiView Answer on Stackoverflow
Solution 25 - Androidcoolcool1994View Answer on Stackoverflow
Solution 26 - AndroidOscar Emilio Perez MartinezView Answer on Stackoverflow
Solution 27 - AndroidCüneytView Answer on Stackoverflow
Solution 28 - AndroidJeffrey ChenView Answer on Stackoverflow
Solution 29 - AndroidAbhishekView Answer on Stackoverflow
Solution 30 - AndroidGk Mohammad EmonView Answer on Stackoverflow
Solution 31 - Androidlogeshpalani31View Answer on Stackoverflow
Solution 32 - AndroidAlireza Haji gholamrezaView Answer on Stackoverflow
Solution 33 - AndroidufdeveloperView Answer on Stackoverflow
Solution 34 - AndroidAndrei RadchenkoView Answer on Stackoverflow
Solution 35 - AndroidMikel PascualView Answer on Stackoverflow
Solution 36 - AndroidanamkinView Answer on Stackoverflow
Solution 37 - AndroidIgorGanapolskyView Answer on Stackoverflow
Solution 38 - AndroidMashiahView Answer on Stackoverflow
Solution 39 - AndroidmadxView Answer on Stackoverflow
Solution 40 - AndroidKaushik GopalView Answer on Stackoverflow
Solution 41 - AndroidZviView Answer on Stackoverflow
Solution 42 - AndroidHansView Answer on Stackoverflow
Solution 43 - AndroidRichard OlthuisView Answer on Stackoverflow
Solution 44 - AndroidManmohan SoniView Answer on Stackoverflow
Solution 45 - AndroidDevendra KulkarniView Answer on Stackoverflow
Solution 46 - Androidwhd.nsrView Answer on Stackoverflow
Solution 47 - AndroidRuben FloresView Answer on Stackoverflow
Solution 48 - AndroidFarido mastrView Answer on Stackoverflow
Solution 49 - AndroidOsama IbrahimView Answer on Stackoverflow
Solution 50 - AndroidFellow7000View Answer on Stackoverflow
Solution 51 - Android10101101View Answer on Stackoverflow
Solution 52 - AndroidProjit RoyView Answer on Stackoverflow
Solution 53 - AndroidAbanoub HanyView Answer on Stackoverflow
Solution 54 - AndroidFedot ParanoicView Answer on Stackoverflow
Solution 55 - Androidsf_adminView Answer on Stackoverflow
Solution 56 - Androidi30mb1View Answer on Stackoverflow