如何解决Android 自定义视图双向绑定不适用于 LiveData
我有一个关于 android 自定义视图中的 livedata 的问题,我有一个带有文本 livedata 的自定义类,它是双向绑定到 xml 但问题是每当用户在 TextInputEditText 中写入任何新值时实时数据的数量没有改变。
class MaterialTextInput @JvmOverloads constructor(
context: Context,attrs: AttributeSet? = null
) : MaterialCardView(context,attrs) {
val viewModel = MaterialTextInputViewModel()
init {
ViewMaterialTextInputBinding.inflate(
LayoutInflater.from(context),this,true
).apply {
viewModel = this@MaterialTextInput.viewModel
}
}
class MaterialTextInputViewModel : ViewModel() {
var text = MutableLiveData("")
}
}
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="viewModel"
type="com.app.utils.views.MaterialTextInput.MaterialTextInputViewModel" />
</data>
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/cardContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="10dp"
app:strokeColor="@{viewModel.text.length() > 0 ? @color/color_4 : @color/white}"
app:strokeWidth="1dp">
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.Dense"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/email_address"
app:boxBackgroundColor="@color/white"
app:boxStrokeWidth="0dp"
app:boxStrokeWidthFocused="0dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/textField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lines="1"
android:text="@={viewModel.text}" />
</com.google.android.material.textfield.TextInputLayout>
</com.google.android.material.card.MaterialCardView>
</layout>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。