如何为相同的绑定编写不同的BindingAdapters

问题描述 投票:1回答:1

假设我正在编写一个显示某种倒计时的应用程序。

// 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?

我能以某种方式指定我想使用哪个适配器吗?

我(应该)编写一个在两个视图之间内部区分的适配器吗?

更好的建议?

android data-binding android-databinding
1个回答
0
投票
为了使代码简单易读,我建议您在以下方法之间进行选择:

    使用一个绑定适配器并向其提供已经准备好的数据-您的逻辑特性将放置在View或ViewModel中。
  1. 使用不同的绑定适配器名称并发布原始数据-所有工作都将放置在每个适配器中。
  • 最适合您的取决于您的需求,格式逻辑的普遍性,当然还有个人的见解。
  • © www.soinside.com 2019 - 2024. All rights reserved.