Search code examples
androiddata-bindingandroid-databinding

Android: Unable to enable/disable Button with ObservableBoolean


The following Observable variables are in ViewModel

var isEmailValid = ObservableBoolean(false)
var isPasswordValid = ObservableBoolean(false)

and set the values in ViewModel on some condition

fun validateUserInputs(email: Boolean, password: Boolean){
    isEmailValid.set(email)
    isPasswordValid.set(password)
}

Finally, accessed from XML layout as below:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="viewModel"
            type="com.packageName.folder.ViewModel" />
    </data>

...

  <com.google.android.material.button.MaterialButton
    android:id="@+id/btnSubmit"
    android:text="@string/sign_in"
    android:enabled="@{viewModel.isEmailValid &amp;&amp; viewModel.isPasswordValid? true: false}" />
...

</layout>

the Button isn't enabled when both Observables are set to true.
Tried viewModel.isEmailValid() and viewModel.isEmailValid()==true options too.

--
What would be the right way to access the said variable in binding XMl?


Solution

  • I got the answer.

    binding.viewModel = viewModel was missing in it's Activity's onCreate().

    So, the following will be the completion of Databinding with ViewModel.

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding = DataBindingUtil.setContentView(this, R.layout.activity_abc)
            binding.viewModel = viewModel
            binding.lifecycleOwner = this
            ...
        }