Home > other >  How do I find a specific fragment in a list of fragments?
How do I find a specific fragment in a list of fragments?

Time:10-29

I have a list of fragments and want to find a specific one based on the fragment type passed in as an argument. Sort of like this:

private fun findFragment(findFragment: Fragment): Fragment {
    fragments.forEach {
        if (it is findFragment) {
            return it
        }
    }
}

findFragment(MyFragment)

I don't want to send an instance but rather the type, and if that type exists in the list, the instance should be returned. I get an error on if (it is findFragment) saying unresolved reference findMyFragment.

How do I make this happen?

CodePudding user response:

Step 1:

ft.replace(R.id.content_frame, fragment, **tag**).commit();

Step 2:

FragmentManager fragmentManager = getSupportFragmentManager();
Fragment currentFragment = fragmentManager.findFragmentById(R.id.content_frame);

Step 3:

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

CodePudding user response:

This error is because your parameter is not a class but only a variable. You can not use instanceof or in this case is to another variable.

The closest solution that is possible in this case is to use the name of your fragment. Something like this:

    private fun findFragment(findFragment: String): Fragment? {
        val fragments = listOf<Fragment>()
        fragments.forEach {
            if (it.javaClass.simpleName == findFragment) {
                return it
            }
        }
        return null
    }

Then you can call this method :

findFragment(MyFragment::class.java.simpleName)
  • Related