Search code examples
androidkotlinbuttonandroid-databinding

Android: Check & Uncheck Switch Button Through DataBinding with LiveData


I'm currently trying to use databinding to set the check state of my Switch button, but for some reason my state never changes?

In my settings page, I do the following:

  1. Check a switch to true
  2. Post value to my livedata variable
  3. Exit Settings page
  4. Re-enter Settings
  5. The Switch should be checked because in my XML i bind to it but it is false.

Files - SettingsFragment - SettingsViewModel - SettingsLayout.XML

SettingsViewModel

    private val _checked = MutableLiveData<Boolean>()
    val checked : LiveData<Boolean> = _checked

SettingsLayout.XML

                <Switch
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right|center"
                android:layout_marginRight="@dimen/margin_big
                android:checked="@{viewModel.checked}"/>

I've double checked to make sure that in my SettingsFragment I do DataBindingUtil.inflate as well and passed my SettingsViewModel.


Solution

  • You need to use Two-way data binding like this:

    android:checked="@={viewModel.checked}"

    Edit: Make sure to add binding.lifecycleOwner = viewLifecycleOwner in your fragment.