Android Two Way DataBinding Problem of Ternary Operator Must be Constant

这一生的挚爱 提交于 2020-12-23 08:20:52

问题


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

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

This is the error I got:

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

UPDATE

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

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

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


回答1:


You need to remove the equal sign before the starting curly brace

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

Also you can use String.valueOf instead of the ``

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



回答2:


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

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)
    }
}
  • Passing multiple arguments from layout to BindingAdapter function: How can I pass multiple arguments via xml for a custom setter when using Android data binding

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

  • The BindingAdapter function is triggered only when using EditText and custom attribute At The Same Time.


来源:https://stackoverflow.com/questions/64596538/android-two-way-databinding-problem-of-ternary-operator-must-be-constant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!