0

My model is extend of androidx.lifecycle.ViewModel not BaseObservable:

import androidx.lifecycle.ViewModel
class MainViewModel: ViewModel() {
    val price:String? = null
}

XML:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@={viewModel.price}"/>

Activity:

val binding: ActivityMainBinding = ...
binding.viewModel = viewModel 
binding.setLifecycleOwner(this)

Is there any way to apply textwatcher to format currency in real time when user typing number?

Sumit Shukla
  • 4,116
  • 5
  • 38
  • 57
Quy Nguyen
  • 159
  • 1
  • 12
  • Possible duplicate of [How to databind to onTextChanged for an EditText on Android?](https://stackoverflow.com/questions/33798426/how-to-databind-to-ontextchanged-for-an-edittext-on-android) – denvercoder9 Sep 20 '19 at 08:20
  • @sonnet it is not since my model is extend of androidx.lifecycle.ViewModel not BaseObservable – Quy Nguyen Sep 20 '19 at 08:25
  • Where did you see a reference to `BaseObservable`? Please try out the solutions from that link first. – denvercoder9 Sep 20 '19 at 08:27
  • The solution on that link are for the model based on BaseObservable not androidx.lifecycle.ViewModel – Quy Nguyen Sep 20 '19 at 08:29
  • Try this: https://developer.android.com/topic/libraries/data-binding/two-way#converters – Yamashiro Rion Sep 20 '19 at 08:58
  • @Yamashiro Rion Thanks for comment. I just tried and it does not work in this case. – Quy Nguyen Sep 20 '19 at 09:43
  • It's tempting to implement this with databindings, but I'd rather suggest to create a custom component or configuration to handle the formatting within the view directly. Have a look at https://developer.android.com/reference/android/text/InputFilter – tynn Sep 20 '19 at 09:46

1 Answers1

0

create a formatter which takes value of EditText

object Converter {
    @InverseMethod("formatCurrency")
    fun format(
        view: EditText, oldValue: Long,
        value: Long
    ): String {
        // Converts long to String.
    }
}

and then create a bindable text or LiveData which keeps text of EditText by getting it from TextWatcher.

android:text="@={Converter.formatCurrency(viewmodel.yourCurrentText)}"
Zafer Celaloglu
  • 1,438
  • 1
  • 17
  • 28