【问题标题】:Android Two Way DataBinding Problem of Ternary Operator Must be Constant三元运算符的Android双向DataBinding问题必须是常量
【发布时间】:2020-10-29 17:42:59
【问题描述】:

我的EditText是这样的:

<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 变量的任何内容(空字符串),这是在创建ViewModel 类对象时(在init{} 块内)初始化的MutableLiveData&lt;Boolean&gt;

这是我得到的错误:

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

更新

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

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

我猜三元运算不能很好地与双向DataBinding 一起工作。

【问题讨论】:

    标签: android kotlin android-room android-databinding android-viewmodel


    【解决方案1】:

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

    1.创建BindingAdapter函数:

    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)
        }
    }
    

    2。在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 和自定义属性同时时触发。

    【讨论】:

      【解决方案2】:

      你需要删除起始大括号前的等号

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

      你也可以使用String.valueOf代替``

      android:text="@{viewModel.isAddCase ? ``: String.valueOf(viewModel.currentStudent.age)}"    
      

      【讨论】:

      • 但是我需要双向绑定功能,我需要更新 prproperty 变量以供以后使用 Room 数据库,这就是问题所在。
      • 那么,您将currentStudent.ageisAddCase 存储在房间里吗?我就是不知道你的型号
      • isAddCase 决定是“我正在添加(插入)新学生”还是“我正在编辑(更新)现有学生”。因此,如果我要添加一个新学生,我希望 EditText 不显示任何内容,而不是属性 agegpa 的“0”,这是 DataBinding 的默认行为。
      • 你可以通过取消使用viewModel.isAddCase 来稍微改变一下这种行为,并使用android:text="@{viewModel.currentStudent.age &lt;= 0 ? ``: String.valueOf(viewModel.currentStudent.age)}"
      • 但是这样age 在我输入时不会自动更改。这就是我需要的两种方式dataBinding 功能。
      猜你喜欢
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      • 2021-11-03
      • 2016-08-09
      • 2015-05-20
      • 1970-01-01
      相关资源
      最近更新 更多