这就是我试图提供我的ViewModelFactory
的方式:
@Suppress("UNCHECKED_CAST")
@Singleton
class ViewModelFactory @Inject constructor(
private val viewModels: MutableMap<Class<out ViewModel>, Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T = viewModels[modelClass]?.get() as T
}
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)
这就是我绑定ViewModelFactory
的方式:
@Suppress("unused")
@Module
abstract class ViewModelModule {
@Binds
internal abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory
@Binds
@IntoMap
@ViewModelKey(MainViewModel::class)
internal abstract fun mainViewModel(viewModel: MainViewModel): ViewModel
}
我在构建期间收到以下错误:
di/Injector.java:9: error: [Dagger/MissingBinding] java.util.Map<java.lang.Class<? extends androidx.lifecycle.ViewModel>,javax.inject.Provider<androidx.lifecycle.ViewModel>> cannot be provided without an @Provides-annotated method.
从我的Activity
我试图以这种方式接收ViewModelFactory
:
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
我最近遇到了同样的问题。版本Kotlin:1.3.40 Dagger:2.23.2我试着按照这篇文章中提到的解决方案和here
但似乎都没有效果。 Dagger的注释处理器与KAPT不兼容,出于同样的原因,构建失败了。这也在Kotlin issue上更新了。
对我来说,将ViewModelKey
和ViewModelFactory
转换为java都有效。对于Dagger来说,跟踪问题可以在here找到。
更新添加@JvmSuppressWildcards
解决了这个问题。代码如下所示:
private val providers: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>
No need to Downgrade the Kotlin version. As the day of Post my Kotlin version
is : '1.3.40'
Use dagger dependency in build.gradle
apply plugin: 'kotlin-kapt'
//Dagger dependencies
implementation 'com.google.dagger:dagger:2.22.1'
kapt 'com.google.dagger:dagger-compiler:2.22.1'
implementation 'com.google.dagger:dagger-android:2.22'
implementation 'com.google.dagger:dagger-android-support:2.22' // if you use the support libraries
kapt 'com.google.dagger:dagger-android-processor:2.22'
And for Java use the following dagger dependency
//Dagger dependencies
implementation 'com.google.dagger:dagger:2.22.1'
annotationProcessor 'com.google.dagger:dagger-compiler:2.22.1'
implementation 'com.google.dagger:dagger-android:2.22'
implementation 'com.google.dagger:dagger-android-support:2.22' // if you use the support libraries
annotationProcessor 'com.google.dagger:dagger-android-processor:2.22'