我有一个BottomSheetDialogFragment
的布局,如下所示:
<data>
<variable
name="viewModel"
type="com.sample.MyViewModel" />
</data>
<TextView android:id="@+id/tvValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text='@{String.format("%.1f", viewModel.weight)}'/>
<Button android:id="@+id/cmdUpdate"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:onClick="@{() -> viewModel.updateWeight()}"
android:text="@string/update" />
这是kotlin代码:
// MyViewModel
val weight = MutableLiveData<Double>()
fun updateWeight() {
weight.value?.let {
weight.value = (it + 0.1)
}
}
// BottomSheetDialogFragment bind view model
val myViewModel = ViewModelProviders.of(it, factory).get(MyViewModel::class)
binding.viewModel = myViewModel
// code showing BottomSheet:
val fragment = MyBottomSheetFragment()
fragment.show(fragmentManager, "bottomsheet")
第一次打开底片片段,它可以显示重量值,但是当我单击按钮更新重量时,什么也没有发生。从调试器中,我可以看到调用了updateWeight
方法,并且权重值已更改,但是TextView
未更新。在其他DialogFragment上也会发生这种情况。
如果我使用普通的Fragment
,那么相同的代码也可以工作
DialogFragment和DataBinding是否有问题?