假设我正在编写一个显示某种倒计时的应用程序。
// somewhere in my fragment:
fun getCountdown(): LiveData<Int> = viewModel.countdown
// 10 ... 9 ... 8 ... etc.
我现在想将此LiveData绑定到two不同的TextViews。
<TextView
android:id="@+id/countdownTextView"
android:text="@{fragment.getCountdown}" />
<TextView
android:id="@+id/hurryUpTextView"
android:text="@{fragment.getCountdown}" />
如果我只有这两个视图之一,则我的BindingAdapter看起来像这样:
// 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")
}
}
现在,同时使用两个TextViews / Adapters的最优雅的方法是什么?
我是否应该在片段中创建两个将倒计时映射到相应字符串的LiveData?
我能以某种方式指定我想使用哪个适配器吗?
我(应该)编写一个在两个视图之间内部区分的适配器吗?
更好的建议?