如何在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 ?: "")
        }
    }
}