1

I am Trying to Implement the ViewModel patten using AndroidViewModel. I have a some EditText in my view. To make the view model responsible to store data i need to get the data to the view model when it is entered.

One way to do it is make a TextWatcher for each and every EditText and save it to the viewmodel when text is changed. is this the right way to do it?

null pointer
  • 5,874
  • 4
  • 36
  • 66

1 Answers1

0

From what I can understand, the ViewModel handles the Views you have created in your view container (that could be a Fragment or an Activity) without being disturbed by the their life-cycle changes.

To your question: The trick here is that you forward all user interactions on your View to the ViewModel. So, yes TextWatcher will work, but you have to write it on the ViewModel and not on your View. Also, ViewModelHelper contains methods that you can call from your corresponding view's methods (eg. have Activity.onSaveInstanceState() call

https://github.com/inloop/AndroidViewModel/blob/master/library/src/main/java/eu/inloop/viewmodel/ViewModelHelper.java#L162

I do not think you will need to create a TextWatcher for every EditText. Can't you create a TextWatcher that you will assign to all the EditTexts and inside one of it's methods identify which TextView triggered this and act accordingly?

Get Editable id in afterTextChanged event

Community
  • 1
  • 1
George Daramouskas
  • 3,720
  • 3
  • 22
  • 51