I am trying to use some databinding to put in place a MVVM structure.
I have created the following xml file (sample) as for the view:
<data>
<variable
name="LoginVM"
type="org.ledeme.animekeeper.LogginMV"/>
<EditText
android:id = "@+id/input_loggin"
android:text="@{LoginVM.username}"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_marginTop="200sp"
android:layout_centerHorizontal="true"
android:hint="@string/login"
android:width="200sp"
android:inputType="text"
android:textAlignment="center"
android:singleLine="true"
android:lines="1"
android:maxLines="1"
/>
In the View Model (mine is called LogginMV), I defined a
private ObservableField<String> username = new ObservableField<>("");
to bind the text entered by the user to username
I use username.get()
to try and get the username but I only get ""
(I know this is due to the value between the parenthesis in new ObservableField<>("")
, if it was "test", I would get "test")
I did create a getter and setter as follow:
public String getUsername(){
return username.get();
}
public void setUsername(ObservableField<String> username) {
this.username = username;
this.username.notifyChange();
}
My problem is that I can't figure out how to correctly do the binding so I get what the user inputted instead of what I define in new ObservableField<>("")
.
I found a tweak that works great :
in the view (xml file) add this :
android:afterTextChanged="@{(edtitable)->LoginVM.afterUserNameChange(edtitable)}"
this will trigger the function afterUserNameChange
in the view model.
public void afterUserNameChange(CharSequence s)
{
//Log.i("truc", s.toString());
this.usrNm = s.toString();
}
this function is triggered after each input the user do in the EditText