I am having trouble understanding how the Fragment + ViewModel paradigm works with a View like an EditText.
It being an EditText, it's gonna obviously be modified within the View (Fragment). But I also want to be able to modify it within the ViewModel: e.g. to erase its text.
Here's the code in the Fragment class:
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
...
comment = mViewModel.getComment();
comment.observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(String s) {
commentView.setText(s);
}
});
...
commentView.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
mViewModel.setComment(String.valueOf(s));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
});
As you can see, I set an observer so when I change the value of the MutableLiveData, the View changes. And I set a watcher so when I (when using the App) change the value of the View, the MutableLiveData changes.
Here's the code of the ModelView class:
public void addRegister() {
...
String comment = this.comment.getValue();
...
this.comment.setValue("");
When I run the App no error pops up, but it hangs. I guess because of an infinite loop. How should I approach EditTexts with this View + ViewModel paradigm? What am I not understanding?
Thanks a lot in advance!