Android数据绑定:context还是ContextCompat?

时间:2019-05-07 15:01:56

标签: android android-context android-databinding android-viewmodel

例如,如果我将Android数据绑定与ViewModel一起使用以设置视图的颜色,那么我有几个选择:

<View ... 
    background="@color/foo" />

class MyViewModel(context: Application): AndroidViewModel(context) {
    // this is a dramatic oversimplification, but for illustration purposes...
    fun theColor: Int = ContextCompat.getColor(context, R.color.foo)
}
<View ... 
    background="@{viewModel.theColor}" />

class MyViewModel(context: Application): AndroidViewModel(context) {
    fun theColor: Int = R.color.foo
}
<View ... 
    background="@{context.getColor(viewModel.theColor)}" />

假设主题对我很重要,这会有所作为吗?具体来说,我的意思是数据绑定表达式使用ContextCompat返回的颜色与Context返回的颜色之间的差异。

0 个答案:

没有答案