0

I am learning how to develop using MVVM. I created a small example as shown below in the code. I want to change the value of the TextView when a UI button is clicked. initially the TextView is set to an empty String.

In the xml file, the TextView UI is bound to a varibale "result" in the Viewmodel, initially this variable "result" is set to " ". What I want to do is, when the user clicks the button, the variable "result" will have another value and I want to set this value to the TextView.

Please let me know how can I achieve it.

xml

<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bind="http://schemas.android.com/tools">

<data>
    <!-- the class the behaves as Viewmodel and contains the @Bindable Object-->
    <variable
        name="vm1"
        type="com.example.amrbakri.mvvm_02.LoginViewModel1" />
</data>


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/actMain_LoginViewModel1_tv_results"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="visible"
        android:text="@{vm1.result}"
        />
</LinearLayout>
</layout>

viewmodel

public class LoginViewModel1 extends BaseObservable {
private final static String TAG = LoginViewModel1.class.getSimpleName();
private final static String MSG_ON_OBSERVATION_RESULTS_SUCCESSFUL = "observation results successful";
private final static String MSG_ON_OBSERVATION_RESULTS_FAILED = "observation results failed";

private String mUserId = null;
private String mUserPass = null;
private UserModel mUserModel = null;

public String result = " ";

public LoginViewModel1() {
    this.mUserModel = new UserModel("", "");
}

public void onLoginUser1Clicked() {
    Log.d(TAG, "onLoginUser1Clicked");
    this.result = "result";
    Log.d(TAG, "onLoginUser1Clicked result: " + this.result);
}
}
user10776303
  • 241
  • 6
  • 16

1 Answers1

0

You need to 'notify data change' event when using DataBinding without any ObservableField or LiveData

I.e. notifyPropertyChanged(BR.vm1)).

So do something like :

public void onLoginUser1Clicked() {
    Log.d(TAG, "onLoginUser1Clicked");
    this.result = "result";
    Log.d(TAG, "onLoginUser1Clicked result: " + this.result);
    notifyPropertyChanged(BR.vm1)); // This will notify data and update UI.
}
Jeel Vankhede
  • 11,592
  • 2
  • 28
  • 58