如何解决与Android中的自定义对象进行双向数据绑定
我正在尝试2种方式进行数据绑定:
XML:
<layout
xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="viewModel"
type="com.example.myApp.AddDoctorViewModel" />
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AddDoctorActivity">
:
:
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/dr_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="Name"
app:boxBackgroundColor="@android:color/transparent">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@={viewModel.doctor.name}"
android:inputType="textPersonName" />
</com.google.android.material.textfield.TextInputLayout>
:
:
</RelativeLayout>
</layout>
视图模型:
public class AddDoctorViewModel extends ViewModel {
public Doctor doctor;
public String name;
}
旋转设备时,写入的文本将不再可用。
我以为我在某个地方做错了,所以我创建了另一个变量
public String name;
在ViewModel类中,将xml中的行从
android:text="@={viewModel.doctor.name}"
至
android:text="@={viewModel.name}"
而且效果很好
我无法理解为什么自定义对象没有进行数据绑定?以及如何解决?
自定义对象“医生”非常简单:
public class Doctor {
String name,email,specializations;
//getters and setters
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。