android - 如何使用 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)}"/>
解决方案
使用带密码的双向数据绑定TextView
,这样您就可以LiveData
在ViewModel
. 然后只需在调用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" />
推荐阅读
- python - Pandas - 众多条件列表,带有逻辑运算符,与“选择”语句一起使用
- php - 在数组中分组日期
- windows - 我在哪里可以找到 Windows 中的 vimrc 文件?
- java - 在读写原子性、可见性和防止重新排序方面,Java 中的锁、同步、原子变量和 volatile
- ruby-on-rails - Rails- Mongoid 查询根据字段长度过滤对象
- php - 如何在在线服务器上运行 Laravel API
- c# - 我需要从 Xamarin 应用程序连接远程数据库
- amazon-cloudformation - 是否可以在 CloudFormation 中重用预先构建的文本?
- jquery - Blueimp 上传,至少需要一个文件
- ios - UITapGestureRecognizer 不适用于自定义视图类