EditText 中的更改不会通过数据绑定更改 StateFlow 数据



我在数据绑定和StateFlow方面有问题。视图和模型绑定在一起,当我将数据输入到编辑文本中时,我在视图模型中的对应变量中没有看到这种变化。这是代码:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="model"
type="ru.home.swap.ui.profile.ProfileViewModel" />
<variable
name="provider"
type="ru.home.swap.providers.PersonProvider" />
</data>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/blue_dark">
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/contact_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="24dp"
android:paddingEnd="24dp"
android:paddingBottom="16dp"
android:layout_below="@id/sign_in"
>
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:hint="Enter your cell or email"
android:text="@{model.name}"
tools:text="+7 910 900 87 70" />
</com.google.android.material.textfield.TextInputLayout>
</FrameLayout>
</layout>

ViewModel

private val _name = MutableStateFlow<String>("")
val name: StateFlow<String> = _name
fun createAnAccount() {
Log.d(App.TAG, "Update name $name")
}

片段中的链接视图和模型

binding.model = viewModel/*viewModel.uiState.value*/
binding.lifecycleOwner = this
binding.confirm.setOnClickListener {
viewModel.createAnAccount()
}

我检查了文件,一切看起来都很好

你看到这里有问题吗?

您没有在文本属性中使用=,这就是为什么它是单向数据绑定。要实现双向数据绑定,您需要像这样使用=

android:text="@={model.name}"

现在试试这个,它应该会起作用。双向数据绑定文档

最新更新