Search code examples
androidkotlinmvvmdata-bindingviewmodel

How to use a view's reference in xml to pass arguments to a function using data binding?


I am using data binding to call a function of my viewmodel but the function requires the values of the edittext. But I don't know how to pass the value of other views.

Here is the xml code. In this I want to pass the value of password edittext to viewmodel on click of the button. Suggest me a way to do this other than using onclickListeners in fragment and calling the function from there.

 <com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/small_margin"
            android:hint="@string/password_hint">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/password_input"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword" />

        </com.google.android.material.textfield.TextInputLayout>

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/login_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/big_action_button_red"
            android:text="@string/login_button_text"
            android:onClick="@{()->viewModel.validateUser(password_input.text)}"/>


Solution

  • Use Two-way data binding with the password TextView, that way you can have the current value of the field in a LiveData in your ViewModel. Then simply get that value inside your ViewModel when validate() is called.

    <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/password_input"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@={viewmodel.passowrd}"
                    android:inputType="textPassword" />