Android DataBinding LiveData - 不通知在 DialogFragment 和 BottomSheetDialogFragment 中更改

Android DataBinding LiveData - not notify changed in DialogFragment & BottomSheetDialogFragment

我有一个 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" />

这里是科特林代码:

  // 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 fragment,它可以显示权重值,但是当我点击按钮更新权重时,没有任何反应。从调试器中,我可以看到调用了 updateWeight 方法,并且更改了权重值,但是 TextView 没有更新。这也发生在其他 DialogFragment 上。
如果我使用普通 Fragment
,相同的代码可以工作 DialogFragment & DataBinding 有问题吗?

您需要致电

binding.setLifecycleOwner(this)

根据 documentation,它允许在 LiveData 更改时更新您的视图。