我的代码:
@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
}
}
@Module
abstract class ActivityBuildersModule {
@ContributesAndroidInjector(
modules = [MainActivityViewModelModule::class]
)
abstract fun contributeMainActivity(): MainActivity
}
@Module
abstract class MainActivityViewModelModule {
@Binds
@IntoMap
@ViewModelKey(MainActivityViewModel::class)
public abstract fun bindMainActivityViewModel(mainActivityViewModel: MainActivityViewModel): ViewModel
}
class MainActivityViewModel @Inject constructor(application: Application) : AndroidViewModel(application) {
// empty for now
}
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@MapKey
public @interface ViewModelKey {
Class<? extends ViewModel> value();
}
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])接口...
扩展DaggerAppCompatActivity而不是AppCompatActivity
我在这里可能是错误的,但是我认为您需要在viewModelModule中使用一个ViewModelFactory,如下所示: