android - 如何在 viewModel 中使用双向绑定
问题描述
我的片段中有一个EditText
,我想将文本值EditText
与 viewModel 的变量双向绑定,这样我就可以在 viewModel 中获取这个文本值来做一些额外的工作。
视图模型:
class MyViewModel @ViewModelInject constructor(
private val myRepository: MyRepository,
private val myPreferences: MyPreferences
) : ViewModel() {
val name = myPreferences.getStoredName()
fun buttonSubmit() {
viewModelScope.launch(Dispatchers.IO) {
myPreferences.setStoredName(name)
val response = myRepository.doSomething(name) // I can get the text value by name variable
}
}
xml:
<layout ...>
<data>
<variable
name="viewModel"
type=".MyViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
...>
<EditText
...
android:text="@={viewModel.name}" /> <!-- how to two-way binding name -->
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
解决方案
您只需要定义name
为MutableLiveData
. 因此,所有文本更改EditText
都会反映到它,您将能够读取如下值buttonSubmit
:(您的xml
内容是正确的)
class MyViewModel @ViewModelInject constructor(
private val myRepository: MyRepository,
private val myPreferences: MyPreferences
) : ViewModel() {
val name = MutableLiveData(myPreferences.getStoredName())
fun buttonSubmit() {
viewModelScope.launch(Dispatchers.IO) {
myPreferences.setStoredName(name.value ?: "")
val response = myRepository.doSomething(name.value ?: "")
}
}
}
推荐阅读
- java - 如何在另一个 Spring Boot 项目中添加本地 Spring Boot 项目作为依赖项
- c++ - 使用 Eigen 迭代二维数组的行或列
- php - php查询安装
- c++ - 从扬声器录制并通过按键结束录制过程,而不是等待指定的时间
- javascript - Laravel 通知铃
- tensorflow - 图像分类的负面例子?
- python - 熊猫 - 与丢弃重复相反,保持第一
- coldfusion - 谷歌 g 套件无效的给定/姓氏:FamilyName (ColdFusion/HTTP POST)
- android - TimeoutException android.media.SoundPool.finalize()
- android - 即使在达到 maxLength 之后,Edittext 也需要字符