I created BindingAdapters for an EditText like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@BindingAdapter("android:text") fun setText(editText: EditText, inputAmount: MutableStateFlow<Double>) { if (editText.text.toString() != inputAmount.value.toString()) { editText.setText(inputAmount.value.toString()) editText.setSelection(editText.text.length) } } @InverseBindingAdapter(attribute = "android:text") fun getText(editText: EditText): Double { if (editText.text.isEmpty()) return 0.0 return editText.text.toString().toDouble() } |
My XML layout element looks like this:
1 2 3 4 5 6 7 |
<com.google.android.material.textfield.TextInputEditText android:id="@+id/tiet_input_amount" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/input_hint_amount" android:inputType="numberDecimal" android:text="@={viewModel._inputAmount}" /> |
And in my ViewModel, the inputAmount
is set up this way:
1 2 |
val _inputAmount: MutableStateFlow<Double> = MutableStateFlow(0.0) val inputAmount: StateFlow<Double> = _inputAmount |