我在android项目中使用dagger 2(版本2.15)进行依赖注入。
除了注入viewmodelfactory之外,一切正常。
我不能把它注射到我的碎片里。
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private val mainViewModel: StationsViewModel by lazy {
ViewModelProviders.of(this, viewModelFactory)
.get(StationsViewModel::class.java)
}
我得到以下错误:
lateinit property viewModelFactory has not been initialized
我有ViewModel模块:
@Module
抽象类viewmodelmodule{
@Binds
@IntoMap
@ViewModelKey(MainViewModel::class)
internal abstract fun bindsMainViewModel(mainViewModel: MainViewModel): ViewModel
@Binds
abstract fun bindViewModelFactory(factory: MyViewModelFactory): ViewModelProvider.Factory
}
视图模型键
@MustBeDocumented
@Target(
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER
)
@Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)
和ViewModelFactory
@Singleton
class MyViewModelFactory @Inject constructor(
private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val creator = creators[modelClass] ?: creators.entries.firstOrNull {
modelClass.isAssignableFrom(it.key)
}?.value ?: throw IllegalArgumentException("unknown model class $modelClass")
try {
@Suppress("UNCHECKED_CAST")
return creator.get() as T
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
虽然我不太明白他们在做什么。
最佳答案
是否可以尝试在onviewcreated()中初始化?
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
mainViewModel = ViewModelProviders.of(this, viewModelFactory)
.get(StationsViewModel::class.java)
// binding.viewmodel = viewModel
}
应该没事的。