如何为相同的绑定编写不同的 BindingAdapter
How to write different BindingAdapters for same binding
假设我正在编写一个显示某种倒计时的应用程序。
// 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")
}
}
现在,将两者 TextViews/Adapters 一起使用的最优雅的方法是什么?
我是否应该在我的片段中创建两个 LiveData,将倒计时映射到适当的字符串?
我能以某种方式指定我想使用哪个适配器吗?
我应该(尝试)编写一个在内部区分两个视图的适配器吗?
更好的建议?
为了使代码简单易读,我建议您在以下方法之间进行选择:
- 使用一个绑定适配器并向其提供已准备好的数据 - 您的逻辑将被放置在 View 或 ViewModel 中。
- 使用不同的绑定适配器名称和 post 原始数据 - 所有工作都将放在每个适配器中。
什么最适合您取决于您的需求、格式逻辑的普遍程度,当然还有个人意见。
假设我正在编写一个显示某种倒计时的应用程序。
// 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")
}
}
现在,将两者 TextViews/Adapters 一起使用的最优雅的方法是什么?
我是否应该在我的片段中创建两个 LiveData,将倒计时映射到适当的字符串?
我能以某种方式指定我想使用哪个适配器吗?
我应该(尝试)编写一个在内部区分两个视图的适配器吗?
更好的建议?
为了使代码简单易读,我建议您在以下方法之间进行选择:
- 使用一个绑定适配器并向其提供已准备好的数据 - 您的逻辑将被放置在 View 或 ViewModel 中。
- 使用不同的绑定适配器名称和 post 原始数据 - 所有工作都将放在每个适配器中。
什么最适合您取决于您的需求、格式逻辑的普遍程度,当然还有个人意见。