我的片段中有一个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 ?: "")
}
}
}