【发布时间】:2020-05-11 10:57:56
【问题描述】:
假设我正在编写一个显示某种倒计时的应用程序。
// somewhere in my fragment:
fun getCountdown(): LiveData<Int> = viewModel.countdown
// 10 ... 9 ... 8 ... etc.
我现在想将此 LiveData 绑定到两个不同的 TextView。
<TextView
android:id="@+id/countdownTextView"
android:text="@{fragment.getCountdown}" />
<TextView
android:id="@+id/hurryUpTextView"
android:text="@{fragment.getCountdown}" />
如果我只有这两个视图之一,我的 BindingAdapter(s) 将如下所示:
// for the countdown-TextView:
@BindingAdapter("android:text")
fun bindCountdownToTextView(view: TextView, state: LiveData<LoggedInSubState>) {
view.setText("$ Seconds remaining!")
}
// OR for the hurry-up-TextView:
@BindingAdapter("android:text")
fun bindCountdownToTextView(view: TextView, state: LiveData<LoggedInSubState>) {
if(state.value < 3){
view.setText("Hurry up!")
} else {
view.setText("Chill, you have a lot of time")
}
}
现在,同时使用两个 TextView/Adapter 最优雅的方式是什么?
我是否应该在片段中创建两个 LiveData,将倒计时映射到适当的字符串?
我能以某种方式指定我想使用哪个适配器吗?
我应该(尝试)编写一个在内部区分两个视图的适配器吗?
更好的建议?
【问题讨论】:
标签: android data-binding android-databinding