-1

Assume I have a fragment called "LoginFragment". I want to use this fragment in add transaction below:

fTransaction.add(R.id.login_fragment, LoginFragment())

But I need call it by name dynamically like this:

val name = "LoginFragment"
fTransaction.add(R.id.login_fragment, name())

How should I do this? Thank you

Sergio
  • 27,326
  • 8
  • 128
  • 149
weera
  • 884
  • 1
  • 10
  • 21
  • 1
    Kotlin is statically-typed language, you can't do dynamic typing here, the Types are resolved at compile-time. – Animesh Sahu Jul 27 '20 at 05:15
  • You could however make a checking function `operator fun String.invoke(): Fragment { if(this == "LoginFragment") return LoginFragment() else throw IllegalArgumentException("Message") }` or you could chain them using a `when` instead of `if`. – Animesh Sahu Jul 27 '20 at 05:18

1 Answers1

1

If you want to instantiate a Fragment by it's name you can use FragmentFactory to instantiate the Fragment:

try {
    val fragmentName = "LoginFragment"
    val fragmentFullName = "your.package.name.$fragmentName"
    val fragment = supportFragmentManager.fragmentFactory.instantiate(classLoader, fragmentFullName)
    supportFragmentManager
            .beginTransaction()
            .add(R.id.login_fragment, fragment)
            .commitNow()
} catch (e: java.lang.Exception) {
    e.printStackTrace()
}
Sergio
  • 27,326
  • 8
  • 128
  • 149