【发布时间】:2018-09-24 23:17:45
【问题描述】:
我有一个这样的 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")
第一次打开bottomsheet片段,它可以显示重量值,但是当我点击按钮更新重量时,没有任何反应。从调试器可以看到updateWeight方法被调用了,权重值改变了,但是TextView没有更新。这也发生在其他 DialogFragment 上。
如果我使用普通的Fragment
,相同的代码可以工作
DialogFragment & DataBinding 有问题吗?
【问题讨论】:
标签: android kotlin android-databinding android-livedata android-viewmodel