Android Two Way DataBinding Problem of Ternary Operator Must be Constant

后端 未结 2 1631
一生所求
一生所求 2020-12-20 06:48

My EditText is like this:



        
相关标签:
2条回答
  • 2020-12-20 07:31

    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.
    0 讨论(0)
  • 2020-12-20 07:32

    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)}"    
    
    0 讨论(0)
提交回复
热议问题