[英]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.这是xml代码。 In this I want to pass the value of password edittext to viewmodel on click of the button.
在此,我想通过单击按钮将密码 edittext 的值传递给 viewmodel。 Suggest me a way to do this other than using onclickListeners in fragment and calling the function from there.
除了在片段中使用 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)}"/>
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
.使用密码为
TextView
的双向数据绑定,这样您就可以在ViewModel
的LiveData
中拥有该字段的当前值。 Then simply get that value inside your ViewModel
when validate()
is called.然后在调用
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" />
Just create string variable in your viewmodel
for password field like this只需在您的
viewmodel
为密码字段创建字符串变量,就像这样
var password:String?=null
Now add this in password_input
field just like this现在像这样在
password_input
字段中添加它
android:text="@={viewmodel.password}" // this directly assign value of password field to password variable
Now at last remove parameter in validateUser
method and directly use password
variable in this method.现在最后删除
validateUser
方法中的参数并在该方法中直接使用password
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.