Get the current fragment object

Viewed 342983

In my main.xml I have

  <FrameLayout
        android:id="@+id/frameTitle"
        android:padding="5dp"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:background="@drawable/title_bg">
            <fragment
              android:name="com.fragment.TitleFragment"
              android:id="@+id/fragmentTag"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content" />

  </FrameLayout>

And I'm setting fragment object like this

FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment newFragment = new FragmentType1();
fragmentTransaction.replace(R.id.frameTitle, casinodetailFragment, "fragmentTag");

// fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

It is setting different types of Fragment objects (FragmentType2,FragmentType3,...) at different time. Now at some point of time I need to identify which object is currently there.

In short I need to do something like this:

Fragment currentFragment = //what is the way to get current fragment object in FrameLayout R.id.frameTitle

I tried the following

TitleFragment titleFragmentById = (TitleFragment) fragmentManager.findFragmentById(R.id.frameTitle);

and

    TitleFragment titleFragmentByTag = (TitleFragment) fragmentManager.findFragmentByTag("fragmentTag");

But both the objects (titleFragmentById and titleFragmentByTag ) are null
Did I miss something?
I'm using Compatibility Package, r3 and developing for API level 7.

findFragmentById() and findFragmentByTag() will work if we have set fragment using fragmentTransaction.replace or fragmentTransaction.add, but will return null if we have set the object at xml (like what I have done in my main.xml). I think I'm missing something in my XML files.

19 Answers

I think you can use onAttachFragment event may be useful to catch which fragment is active.

@Override
public void onAttachFragment(Fragment fragment) {
    // TODO Auto-generated method stub
    super.onAttachFragment(fragment);

    Toast.makeText(getApplicationContext(), String.valueOf(fragment.getId()), Toast.LENGTH_SHORT).show();

}
  1. Do a check (which fragment in the activity container) in the onStart method;

    @Override
    protected void onStart() {
    super.onStart();
    Fragment fragmentCurrent = getSupportFragmentManager.findFragmentById(R.id.constraintLayout___activity_main___container);
    }
    
  2. Some check:

    if (fragmentCurrent instanceof MenuFragment) 
    

If you are extending from AbstractActivity, you could use the getFragments() method:

for (Fragment f : getFragments()) {
    if (f instanceof YourClass) {
        // do stuff here
    }
}

This will give you the current fragment class name -->

String fr_name = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();

you can check which fragment is currently loaded by this

        supportFragmentManager.addOnBackStackChangedListener {
        val myFragment = supportFragmentManager.fragments.last()

        if (null != myFragment && myFragment is HomeFragment) {
            //HomeFragment is visible or currently loaded
        } else {
            //your code
        }
    }

I use the following function in Kotlin:

supportFragmentManager.fragments.run {
    getOrNull(size - 1)?.let { currentFragment ->
        ...
    }
}

I recently worked on an activity involving multiple fragments so thought to share the method I used here:

Firstly, I declared a function getCurrentFragment() which returned me, yeah you guessed it, the current fragment, lol.

private fun getCurrentFragment(): Fragment? {
    return supportFragmentManager.findFragmentById(R.id.fragmentContainerView)
}

Then I override the onBackPressed function in the activity to define the navigation within fragments. Suppose, I wanted to show fragment 2 if user is in fragment 3 and presses back so I did something like this to achieve this

override fun onBackPressed() {
        if (getCurrentFragment() is Fragment3) {
            showFragment2()
        } else {
            super.onBackPressed()
        }
    }

And in showFragment2() I did something like this:

private fun showFragment2() {
        val fragment = Fragment2.newInstance()
        supportFragmentManager.commit {
            replace(R.id.FragmentContainerView, fragment, "Add a tag here")
        }
    }

I think this should give better idea to people looking on how to navigate through fragments within an activity.

Related