如何在viewModel

问题描述

我的片段中有一个EditText,我想将EditText的文本值与viewModel变量进行双向绑定,以便可以在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 ?: "")
        }
    }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...