Android中带有Kotlin的匕首:lateinit属性viewModelProviderFactory尚未初始化

问题描述 投票:0回答:2

我的代码:

  1. 应用组件:
@Component(
    modules = [
        AndroidSupportInjectionModule::class,
        ActivityBuildersModule::class,
        ViewModelFactoryModule::class
    ]
)
interface AppComponent : AndroidInjector<BaseApplication> {

    @Component.Builder
    interface Builder {

        @BindsInstance
        fun application(application: Application): Builder

        fun build(): AppComponent
    }
}
  1. ActivityBuildersModule:
@Module
abstract class ActivityBuildersModule {

    @ContributesAndroidInjector(
        modules = [MainActivityViewModelModule::class]
    )
    abstract fun contributeMainActivity(): MainActivity
}
  1. MainActivityViewModelModule:
@Module
abstract class MainActivityViewModelModule {

    @Binds
    @IntoMap
    @ViewModelKey(MainActivityViewModel::class)
    public abstract fun bindMainActivityViewModel(mainActivityViewModel: MainActivityViewModel): ViewModel
}
  1. MainActivityViewModel:
class MainActivityViewModel @Inject constructor(application: Application) : AndroidViewModel(application) {
   // empty for now
}
  1. ViewModelKey(在Java中:)]
  2. @Documented
    @Target({ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @MapKey
    public @interface ViewModelKey {
    
        Class<? extends ViewModel> value();
    }
    
  1. MainActivity:
  2. class MainActivity : AppCompatActivity() {
    
    //  doesn't work for now
        @Inject
        lateinit var viewModelProviderFactory: ViewModelProviderFactory
    
        lateinit var mainActivityViewModel: MainActivityViewModel
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            setContentView(R.layout.activity_main)
    
            mainActivityViewModel = ViewModelProvider(this, viewModelProviderFactory).get(MainActivityViewModel::class.java)
    
            setMainFragment()
        }
    
        private fun setMainFragment() {
            // my code
        }
    }
    

它给我一个错误:lateinit属性viewModelProviderFactory尚未初始化。

相同的代码在Java中的另一个项目中也可以正常工作。

我的代码:App Component:@Component(modules = [AndroidSupportInjectionModule :: class,ActivityBuildersModule :: class,ViewModelFactoryModule :: class])接口...

android kotlin dagger
2个回答
0
投票

扩展DaggerAppCompatActivity而不是AppCompatActivity


0
投票

我在这里可能是错误的,但是我认为您需要在viewModelModule中使用一个ViewModelFactory,如下所示:

© www.soinside.com 2019 - 2024. All rights reserved.