0

I have an EditText and i want to do some action every time the user inserts a value.

In the old times, before databinding with LD, I would just have a method in my Activity which performs the action, and reference it in the layout like this:

In Layout:

<EditText
      android:onTextChanged="textChanged()"

Now i´m using databinding with LiveData. I have a field in my VM referenced from the UI, and using two-way databinding, so the field is updated automatically. But what if i want to do something more than just updating the value of the field? Can i define a method to run other actions, like for example save the value in the database?

In Layout:

<EditText
      android:text="@={viewmodel.myField}"

In ViewModel:

val myField = MutableLiveData<String>()

*Note: I want it to be done in the VM. I know i could create an observer in the Activity observing the field in the VM, but that is just if i want some UI change done. I want to do some business logic when the value changes, not UI.

Gio
  • 190
  • 2
  • 11
  • so you want to get notified about `onTextChanged` inside your VM? – Saeed Masoumi Jun 01 '19 at 09:41
  • I want to have the same functionality, yes. But not using `onTextChanged` as i am using two-way databinding. – Gio Jun 01 '19 at 09:50
  • Why don't you use `android:onTextChanged="@{vm.textChanged()}"`? – Saeed Masoumi Jun 01 '19 at 09:54
  • add a ```textChangedListener``` to your ```EditText``` https://stackoverflow.com/questions/33798426/how-to-databind-to-ontextchanged-for-an-edittext-on-android/55701091#55701091 – mahdi shahbazi Jun 01 '19 at 11:01
  • @mahdishahbazi Yes, i thought of adding a bind adapter... but is there not an out of the box solution? I thought i could use getters/setters in the model when the value changes or something like that... – Gio Jun 01 '19 at 11:05
  • what's your meaning of out of the box solution? Is it something like getting changes in your activity?? – mahdi shahbazi Jun 01 '19 at 13:03
  • The purpose of two-way databinding is to make my ViewModel change automatically when the UI changes, without implementing event listeners or anything like that. I could have a listener, yes, but then what´s the point of having databinding? If i am implementing a method triggered from the UI, i could just set the value in that method, i wouldn´t need to set `android:text="@={viewmodel.myField}"` What i need is a way to control how the value is set in the ViewModel, having a setter method which is run AFTER the databinding process has taken place. – Gio Jun 01 '19 at 13:22
  • You can observe `myField` in ViewModel using `.observeForever()` method. No need to create anything in View layer – Sanlok Lee Jun 01 '19 at 20:39

0 Answers0