View enablement not working when using two-way databinding and Livedata

Viewed 40

I would like to enable a EditText field depending on a CheckBox being checked or not:

enter image description here enter image description here

The app works as expected until I start using LiveData to enable/disable the checkbox (disabling the checkbox no longer set the EditText to enabled=false). Result Checkbox unchecked, EditText field still enabled:

enter image description here

The Viewmodel code:

class FirestoreViewModel : ViewModel() {

var firebaseRepository = FirestoreRepository()

val userItem = firebaseRepository.getUserItem() as MutableLiveData<UserItem>}

The Activity code (binding the layout and the viewmodel):

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    //to show problem: binding = FragmentLivedataBinding.inflate(layoutInflater)
    val binding = FragmentNoLivedataBinding.inflate(layoutInflater)

    binding.lifecycleOwner = this

    val model: FirestoreViewModel by viewModels()

    binding.viewmodel = model

    setContentView(binding.root)
}

The layout.xml file using LiveData to set the CheckBox (FragmentLivedata):

<CheckBox
                android:id="@+id/checkBox1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:checked="@={viewmodel.userItem.player1Active}"/>

            <EditText
                android:id="@+id/textView1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:importantForAutofill="no"
                android:inputType="textPersonName"
                android:text="@={viewmodel.userItem.player1Name}"
                android:enabled="@{viewmodel.userItem.player1Active}"
                tools:text="User Name" />

Without LiveData (FragmentNoLivedata):

<CheckBox
                android:id="@+id/checkBox1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:checked="true"/>

            <EditText
                android:id="@+id/textView1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:importantForAutofill="no"
                android:inputType="textPersonName"
                android:text="@={viewmodel.userItem.player1Name}"
                android:enabled="@{checkBox1.checked}"
                tools:text="User Name" />

Please help me find the proper solution for this issue.

0 Answers
Related