如何使用 xml 中的视图引用将参数传递给使用数据绑定的函数?

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

我正在使用数据绑定来调用我的视图模型的函数,但该函数需要编辑文本的值。但是我不知道如何传递其他视图的值。

这是xml代码。在这里,我想在单击按钮时将密码 edittext 的值传递给 viewmodel。 向我推荐一种方法,而不是在片段中使用 onclickListeners 并从那里调用函数。

 <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)}"/>

使用 Two-way data binding 和密码 TextView,这样您就可以在 ViewModelLiveData 中获得该字段的当前值。 然后,当调用 validate() 时,只需在 ViewModel 中获取该值即可。

<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" />

只需在 viewmodel 中为密码字段创建字符串变量,如下所示

  var password:String?=null

现在像这样在 password_input 字段中添加这个

 android:text="@={viewmodel.password}" // this directly assign value of password field to password variable

现在终于去掉validateUser方法中的参数,直接在这个方法中使用password变量。