Android 三元运算符的双向数据绑定问题必须是常数 [英] Android Two Way DataBinding Problem of Ternary Operator Must be Constant

查看:27
本文介绍了Android 三元运算符的双向数据绑定问题必须是常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的EditText是这样的:

My EditText is like this:

<EditText
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="@={viewModel.isAddCase? ``: `` + viewModel.currentStudent.age}"    //problem here
    android:inputType="number" />

我希望 EditText 不显示基于 isAddCase 变量的任何内容(空字符串),这是一个 MutableLiveData 初始化当 ViewModel 类对象被创建时(在 init{} 块内).

I want the EditText not to show anything (empty String) based on the isAddCase variable, which is a MutableLiveData<Boolean> initilized when the ViewModel class object is created (inside the init{} block).

这是我得到的错误:

The expression '((viewModelIsAddCaseGetValue) ? ("") : (javaLangStringViewModelCurrentStudentAge))' cannot be inverted, so it cannot be used in a two-way binding

Details: The condition of a ternary operator must be constant: android.databinding.tool.writer.KCode@37a418c7


更新

即使这不起作用,也会显示相同的错误:

Even this doesn't work, shows the same error:

android:text="@={viewModel.currentStudent.age == 0? ``: `` + viewModel.currentStudent.age}"

我猜三元运算不适用于双向 DataBinding.

I guess ternary operation just doesn't work well with two-way DataBinding.

推荐答案

好的,这些天后我找到了完美的解决方案:

Ok, I've figured out the perfect solution after these days:

1.创建BindingAdapter函数:

1. Create BindingAdapter Function:

object DataBindingUtil {                                    //place in an util (singleton) class
    @BindingAdapter("android:text", "isAddCase")            //custom layout attribute, see below
    @JvmStatic                                              //required
    fun setText(editText: EditText, text: String, isAddCase: Boolean) {     //pass in argument
        if (isAddCase) editText.setText("") else editText.setText(text)
    }
}

  • 将多个参数从布局传递到 BindingAdapter 函数:如何才能使用 Android 数据绑定时,我通过 xml 为自定义 setter 传递多个参数
  • 2.在 View 中应用自定义属性:

    2. Apply Custom Attribute in View:

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:inputType="number"
        android:text="@={`` + viewModel.currentStudent.age}"        //two-way binding as usual
        app:isAddCase="@{viewModel.isAddCase}" />                   //here
    


    • BindingAdapter 函数仅在使用 EditText 和自定义属性同时时触发.

      • The BindingAdapter function is triggered only when using EditText and custom attribute At The Same Time.
      • 这篇关于Android 三元运算符的双向数据绑定问题必须是常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆