【问题标题】:How to write different BindingAdapters for same binding如何为相同的绑定编写不同的 BindingAdapter
【发布时间】: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


    【解决方案1】:

    为了使代码简单易读,我建议您选择以下方法:

    1. 使用一个绑定适配器并向其提供已经准备好的数据 - 您的逻辑将特别放在 View 或 ViewModel 中。
    2. 使用不同的绑定适配器名称并发布原始数据 - 所有工作都将放在每个适配器中。

    最适合您的取决于您的需求、格式逻辑的常见程度,当然还有个人意见。

    【讨论】:

    • 即使有两个不同的适配器名称,我将如何在适配器之间进行选择?您能否指定“发布原始数据” - 部分?
    • @m.reiter 创建不同的绑定适配器,例如 @BindingAdapter("loggedinSubstate") fun bindCountdownToTextView(view: TextView, state: LiveData&lt;LoggedInSubState&gt;)@BindingAdapter("loggedinSubstate") fun bindCountdownToTextView(view: TextView, state: LiveData&lt;LoggedInSubState&gt;)post raw data - 传递 LiveData&lt;LoggedInSubState&gt; 并在绑定函数中对其进行格式化。
    猜你喜欢
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 2018-05-04
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 2012-01-07
    相关资源
    最近更新 更多