0

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?

crjacinro
  • 135
  • 1
  • 6
Joakim Sjöstedt
  • 824
  • 2
  • 9
  • 18
  • You can try to use that `type` or class name and set that as a tag for the fragment. And then you can just search fragment by tag. Either in your list or using `fragmentManager.findFragmentByTag(tag)` – Ionut J. Bejan Oct 28 '21 at 08:31

1 Answers1

0

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)
crjacinro
  • 135
  • 1
  • 6