Created
February 4, 2019 20:06
-
-
Save kakai248/4381550e37fe8cd25f0d8074b8e4ea7f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Module | |
abstract class FragmentBindingModule { | |
@Binds | |
abstract fun bindFragmentFactory(factory: FragmentInjectionFactory): FragmentFactory | |
@Binds | |
@IntoMap | |
@FragmentKey(MainFragment::class) | |
abstract fun bindMainFragment(fragment: MainFragment): Fragment | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* [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