Skip to content

Instantly share code, notes, and snippets.

@kakai248
Created February 4, 2019 20:06
Show Gist options
  • Save kakai248/4381550e37fe8cd25f0d8074b8e4ea7f to your computer and use it in GitHub Desktop.
Save kakai248/4381550e37fe8cd25f0d8074b8e4ea7f to your computer and use it in GitHub Desktop.
@Module
abstract class FragmentBindingModule {
@Binds
abstract fun bindFragmentFactory(factory: FragmentInjectionFactory): FragmentFactory
@Binds
@IntoMap
@FragmentKey(MainFragment::class)
abstract fun bindMainFragment(fragment: MainFragment): Fragment
}
/**
* [FragmentFactory] class that takes a map of [Fragment] classes and related
* Dagger [Provider] instances to create new [Fragment] instances using dependency injection
*/
@ActivityScope
class FragmentInjectionFactory @Inject constructor(
private val creators: Map<Class<out Fragment>, @JvmSuppressWildcards Provider<Fragment>>
) : FragmentFactory() {
override fun instantiate(classLoader: ClassLoader, className: String, args: Bundle?): Fragment {
val fragmentClass = loadFragmentClass(classLoader, className)
val creator = creators[fragmentClass]
?: throw IllegalArgumentException("Unknown fragment class $fragmentClass")
try {
val fragment = creator.get()
fragment.arguments = args
return fragment
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment