我遇到数据绑定问题
我的ViewModel包含两个属性。一个用于日期,另一个用于文本表示
class MyViewModel(context: Application): AndroidViewModel(context) {
val dateValue = MutableLiveData<Date>()
val dateText = MediatorLiveData<String>().apply {
this.addSource(dateValue) {
it?.let {
this.value = DateHelper.DisplayFormat.format(it)
}
}
}
}
layout包含EditText,它绑定到文本表示
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<import type="android.view.View" />
<variable name="viewModel" type=".MyViewModel" />
</data>
<LinearLayout>
<EditText android:id="@+id/dateText"
android:text="@{ viewModel.dateText }"
android:focusable="false" android:hint="choose" />
</LinearLayout>
</layout>
当我点击EditText时,我会显示设置dateValue
的datepickeroverride fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val listener = DatePickerDialog.OnDateSetListener { _: DatePicker, year: Int, month: Int, dayOfMonth: Int ->
val result = Calendar.getInstance().apply {
this[year, month] = dayOfMonth
}
viewModel.dateValue.value = result.time
}
val c = Calendar.getInstance()
if (dateField.value != null) c.time = viewModel.dateValue.value
return DatePickerDialog(activity!!, listener,
c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH))
}
但是当设置了日期时,EditText中的文本仍为空。 哪里有问题?是否应自动刷新EditText?