我有一个Activity,其中提供了视图抛出ViewModelFactory
ViewModelFactory
@Singleton
class ViewModelFactory @Inject constructor(private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
var creator: Provider<out ViewModel>? = creators.get(modelClass)
if (creator == null) {
for (entry in creators.entries) {
if (modelClass.isAssignableFrom(entry.key)) {
creator = entry.value
break
}
}
}
if (creator == null) {
throw IllegalArgumentException("unknown model class $modelClass")
}
try {
return creator.get() as T
} catch (e: Exception) {
Log.d("ERRORR", e.toString())
throw RuntimeException(e)
}
}
}
活动
class MyActivity: AppCompatActivity(), Injectable, HasSupportFragmentInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
lateinit var viewModel: MyViewModel
@Inject
lateinit var viewModelFactory: ViewModelFactory
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProviders.of(this, viewModelFactory).get(MyViewModel::class.java)
val binding: MyLayoutBinding= DataBindingUtil.setContentView(this, R.layout.my_layout)
}
}
一切正常,但是当我尝试进入分屏显示时,我的活动将我传递给创建ViewModel的新实例。但是,当我关闭拆分屏幕并进入正常模式时,我的活动将返回先前对ViewModel的检查。哪里有问题?
@Module
abstract class ActivityModule {
@Binds
abstract fun activity(activity: MainActivity): Activity
@Binds
abstract fun bindViewModelFactory(factory: MyViewModelFactory): ViewModelProvider.Factory
@Binds
@IntoMap
@ViewModelKey(MainViewModel::class)
abstract fun MyViewModel(mainViewModel: MyViewModel): ViewModel
}
答案 0 :(得分:0)
实际上,您不应将ViewModel
设置为onCreate()
。
您可以立即设置它,也可以使用惰性设置。
private val viewModel: MyViewModel by lazy {
ViewModelProviders.of(this, viewModelFactory).get(MyViewModel::class.java)
}
直接作为您活动的成员之一。