首页 > 解决方案 > 如何使用 xml 中的视图引用将参数传递给使用数据绑定的函数?

问题描述

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

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

标签: androidkotlinmvvmdata-bindingviewmodel

解决方案


使用带密码的双向数据绑定TextView,这样您就可以LiveDataViewModel. 然后只需在调用ViewModel时获取该值。validate()

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

推荐阅读