首页 > 解决方案 > 如何在 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>

标签: androidkotlinandroid-databindingandroid-viewmodeltwo-way-binding

解决方案


您只需要定义nameMutableLiveData. 因此,所有文本更改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 ?: "")
        }
    }
}

推荐阅读