docs/reference/koin-android/fragment-factory.md
Koin integrates with AndroidX FragmentFactory to enable constructor injection in Fragments.
:::info Fragment Factory uses DSL only. Annotation and Compiler Plugin DSL support is not yet available. :::
implementation "io.insert-koin:koin-android:$koin_version"
In your Koin configuration, enable the fragment factory:
startKoin {
androidContext(this@MainApplication)
fragmentFactory()
modules(appModule)
}
Use the fragment DSL keyword with constructor injection:
class MyFragment(
private val myService: MyService
) : Fragment()
val appModule = module {
single { MyService() }
fragment { MyFragment(get()) }
}
Call setupKoinFragmentFactory() before super.onCreate():
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
// Must be called BEFORE super.onCreate()
setupKoinFragmentFactory()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
Use the reified extension function:
supportFragmentManager.beginTransaction()
.replace<MyFragment>(R.id.container)
.commit()
With arguments and tag:
supportFragmentManager.beginTransaction()
.replace<MyFragment>(
containerViewId = R.id.container,
args = bundleOf("key" to "value"),
tag = "my_fragment"
)
.commit()
To use Activity-scoped dependencies in your Fragment:
val appModule = module {
scope<MyActivity> {
scoped { ActivityService() }
fragment { MyFragment(get()) }
}
}
Pass the scope to setupKoinFragmentFactory():
class MyActivity : AppCompatActivity(), AndroidScopeComponent {
override val scope: Scope by activityScope()
override fun onCreate(savedInstanceState: Bundle?) {
// Pass scope to fragment factory
setupKoinFragmentFactory(scope)
super.onCreate(savedInstanceState)
}
}
| Action | Code |
|---|---|
| Declare fragment | fragment { MyFragment(get()) } |
| Setup global factory | setupKoinFragmentFactory() |
| Setup with scope | setupKoinFragmentFactory(scope) |
| Add fragment | .replace<MyFragment>(R.id.container) |