I was trying to view-model in android, so for MainViewModel.java I wrote this :
public class MainViewModel extends ViewModel {
private String textView;
private String editText;
//@Bindable
public String getTextView(){
return textView;
}
private void setTextView(String value){
textView=value;
}
//@Bindable
public TextWatcher getEditTextWatcher() {
return new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
setTextView(s.toString());
}
...
};
}
}
And in the ActivityMain.xml I wrote this :
<TextView
android:text="View-Model / Data-Binding"
android:layout_width="match_parent"
android:layout_height="40dp"/>
<TextView
android:id="@+id/main_text_view"
android:text="@{mainvm.textView}"
android:layout_width="match_parent"
android:layout_height="40dp"/>
<EditText
android:id="@+id/main_edit_text"
app:textChangeListener="@{mainvm.editTextWatcher}"
android:layout_width="match_parent"
android:layout_height="40dp"/>
I'm getting 2 errors:
Cannot find a setter for <android.widget.EditText app:textChangeListener> that accepts parameter type 'android.text.TextWatcher'
If a binding adapter provides the setter, check that the adapter is annotated correctly and that the parameter type matches.
And,
error: cannot find symbol class ActivityMainBindingImpl
Some article uses @Binable annotation extending BaseObservable, which is not a ViewModel thing.
So my question how can I solve this ?
I was making thing complicated for no reason. Here is my code :
public class MyViewModel extends ViewModel{
private Observable<String> data=new Observable<>("");//initializing with empty string, so that it doesn't crash
public String getData(){
return data.get();//if I return the observable itself that will become mutable, outside the class right
}
public void setData(String data){
data.setValue(data);//if I accept Observable as parameter that will change reference of data, that's why passing string
}
}
In xml:
<TextView
android:id="@+id/main_text_view"
android:text="@{myvm.data}"
...
/>
<EditText
android:id="@+id/main_edit_text"
android:text=@{myvm.data}
....
/>
And bind this to Activity or Fragment as usual.