ductran
ductran

Reputation: 10203

Android DataBinding LiveData - not notify changed in DialogFragment & BottomSheetDialogFragment

I have an BottomSheetDialogFragment 's layout like this:

<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" />

And here is the kotlin code:

  // 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")

The first time open bottomsheet fragment, it can show the weight value, but when I click on button to update weight, there is nothing happen. From debugger, I can see that the updateWeight method is called, and the weight value is changed, but the TextView is not updated. This also happens on other DialogFragment.
The same code can work if I use normal Fragment
Is there something wrong with DialogFragment & DataBinding?

Upvotes: 3

Views: 1740

Answers (1)

ConstOrVar
ConstOrVar

Reputation: 2085

You need to call

binding.setLifecycleOwner(this)

According to documentation, it allows to update your view when LiveData was changed.

Upvotes: 9

Related Questions