【发布时间】:2018-09-14 15:55:36
【问题描述】:
我正在尝试新的 Android 架构组件,但在尝试将 MVVM 模型用于自定义视图时遇到了障碍。
基本上我已经创建了一个自定义视图来封装一个通用 UI,它是在整个应用程序中使用的相应逻辑。我可以在自定义视图中设置 ViewModel,但我必须使用 observeForever() 或在自定义视图中手动设置 LifecycleOwner,如下所示,但看起来都不正确。
选项 1) 使用 observeForever()
活动
class MyActivity : AppCompatActivity() {
lateinit var myCustomView : CustomView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
myCustomView = findViewById(R.id.custom_view)
myCustomView.onAttach()
}
override fun onStop() {
myCustomView.onDetach()
}
}
自定义视图
class (context: Context, attrs: AttributeSet) : RelativeLayout(context,attrs){
private val viewModel = CustomViewModel()
fun onAttach() {
viewModel.state.observeForever{ myObserver }
}
fun onDetach() {
viewModel.state.removeObserver{ myObserver }
}
}
选项2)从Activity设置lifecycleOwner`
活动
class MyActivity : AppCompatActivity() {
lateinit var myCustomView : CustomView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
myCustomView = findViewById(R.id.custom_view)
myCustomView.setLifeCycleOwner(this)
}
}
自定义视图
class (context: Context, attrs: AttributeSet) : RelativeLayout(context,attrs){
private val viewModel = CustomViewModel()
fun setLifecycleOwner(lifecycleOwner: LifecycleOwner) {
viewModel.state.observe(lifecycleOwner)
}
}
我只是在滥用模式和组件吗?我觉得应该有一种更简洁的方式来组合来自多个子视图的复杂视图,而不会将它们绑定到 Activity/Fragment
【问题讨论】:
-
为什么不使用
observeForever(observer)来代替?它不需要 LifeCycleOwner 并且您可以删除onDetachedFromWindow()中的 Observer
标签: android mvvm android-architecture-components android-livedata android-viewmodel