我遇到过同样的问题。原来我错过了这个依赖import org.kodein.di.android.x.kodein
(不知道为什么它没有被 IDE 自动添加)
这是Kodein
+AndroidX
库的示例:AndroidManifest.xml
<application
...
android:name=".core.BaseApplication">
应用
open class BaseApplication : Application(), KodeinAware {
override val kodein = Kodein.lazy {
import(androidXModule(this@BaseApplication))
// import(otherCustomModule)
}
}
碎片
import androidx.fragment.app.Fragment
import org.kodein.di.Kodein
import org.kodein.di.KodeinAware
import org.kodein.di.android.x.kodein
import org.kodein.di.generic.kcontext
abstract class InjectionFragment : Fragment(), KodeinAware {
final override val kodeinContext = kcontext<Fragment>(this)
final override val kodein: Kodein by kodein()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
kodeinTrigger?.trigger()
}
}
// usage
class MyFragment() : InjectionFragment() {
val someDependency: Type by instance()
}
依赖项app\build.gradle
implementation "org.kodein.di:kodein-di-generic-jvm:6.3.2"
implementation "org.kodein.di:kodein-di-framework-android-x:6.3.2"
implementation "androidx.appcompat:appcompat:1.0.2"
额外kodeinTrigger
重写属性(来自)
也是值得的KodeinAware
。这样,debug
在创建 Fragment 时,构建的所有依赖项都将得到解决,因此应用程序将立即失败(与release
仅在使用时才解决依赖项的构建相反 - 某些用户路径可能不会使应用程序崩溃)
abstract class InjectionFragment : Fragment(), KodeinAware {
final override val kodeinContext = kcontext<Fragment>(this)
final override val kodein: Kodein by kodein()
final override val kodeinTrigger: KodeinTrigger? // See description in InjectionActivity
get() = if (BuildConfig.DEBUG) KodeinTrigger() else super.kodeinTrigger
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
kodeinTrigger?.trigger()
}
}
编辑:这是我的项目,所有东西都连接在一起https://github.com/igorwojda/Android-Showcase