4

I am using ternary operator on observable field to set the text to textview in xml.But its gives me following error at compile time.

****/ data binding error ****msg:The expression ((vmEnteredAmountGetJavaLangString0) ? ("") : (vmEnteredAmountGet)) cannot be inverted: The condition of a ternary operator must be constant: android.databinding.tool.writer.KCode@1a6539af

Below is my code:

<EditText
                android:id="@+id/txtAmount"
                style="@style/AmountText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text='@={vm.enteredAmount.get()=="0"?"":vm.enteredAmount}'
                app:decimalLen='@{6}' /> 

Any help will be appreciated.Thank you.

Lukas Baliak
  • 2,849
  • 2
  • 23
  • 26
sanil
  • 482
  • 1
  • 7
  • 23

1 Answers1

1

I have this problem too, I think ternary operation doesn't work well with two-way DataBinding. I have following solutions.

Method 1 | Apply to All EditText:

object DataBindingUtil {        //Kotlin singleton class
    @BindingAdapter("android:text")
    @JvmStatic
    fun setText(editText: EditText, text: String?) {
        if (text == "0" || text == "0.0") editText.setText("") else editText.setText(text)
    }
}

Method 2 | Apply to Selected EditText:

object DataBindingUtil {
    @BindingAdapter("emptyIfZeroText")        //use this instead "android:text"
    @JvmStatic
    fun setText(editText: EditText, text: String?) {
        if (text == "0" || text == "0.0") editText.setText("") else editText.setText(text)
    }

    @InverseBindingAdapter(attribute = "emptyIfZeroText", event = "android:textAttrChanged")
    @JvmStatic
    fun getText(editText: EditText) = editText.text.toString()
}

Apply to your EditText: app:emptyIfZeroText="@={`` + viewModel.currentStudent.gpa}"

Sam Chen
  • 7,597
  • 2
  • 40
  • 73