Skip to content

Instantly share code, notes, and snippets.

@jobinlawrance
Last active November 2, 2020 05:52
Show Gist options
  • Save jobinlawrance/5492b4628251574bf020d3d3675a8c66 to your computer and use it in GitHub Desktop.
Save jobinlawrance/5492b4628251574bf020d3d3675a8c66 to your computer and use it in GitHub Desktop.
class MainActivity : AppCompatActivity() {
private val mainfactory = MainFragmentFactory("Now this won't crash")
private lateinit var mainFragment: MainFragment
override fun onCreate(savedInstanceState: Bundle?) {
supportFragmentManager.factory = mainfactory //This has to be done before super call
super.onCreate(savesInstanceState)
mainFragment = supportFragmentManager.fragmentFactory.instantiate(classLoader, MainFragmentFactory::class.java.name)
supportFragmentManager.beginTransaction()
.add(R.layout.fragmentContainerView, mainFragment)
.commit()
}
}
class MainFragmentFactory(val textToDisplay: String): FragmentFactory() {
override fun instantiate(classLoader: ClassLoader, className: String): Fragment {
return when(className) {
NotificationFragment::class.java.name -> MainFragment(textToDisplay)
else -> super.instantiate(classLoader, className)
}
}
}
class MainFragment(val textToDisplay: String) : Fragment() {
// Same as earler, no changes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment