如何在viewModel中使用双向绑定

How to use two-ways binding in 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 ?: "")
        }
    }
}