Search code examples
androidmvvmdata-binding

android visiblity data-binding with two-ways


I am trying to make an expandleMenu which is shown and hidden dynamically by clicking its content.

<LinearLayout
  android:id="@+id/expandableMenu"
  android:visibility='@{vm.isShow? View.VISIBLE : View.GONE}'
  style="@style/LinearVerticalNoPadding">

It works perfect, but if I want to use it as two-way binding. it occurs an error.
android:visiblity='@={isShow? View.VISIBLE : View.GONE}'

The expression '((isShow) ? (android.view.View.VISIBLE) : (android.view.View.GONE))' cannot be inverted, so it cannot be used in a two-way binding

So, I decided to bind visiblity directly with Int type intead of Boolean.
android:visibility='@={vm.showMenu, default=gone}'

But It said,

Cannot find a getter for <android.widget.LinearLayout android:visibility> that accepts parameter type 'int'

Is there a proper way to bind visibility with 2ways binding?


Solution

  • Two way data binding does not work with ternary operator as in two-way data binding not only a variable value is mapped to xml but also xml value is stored back in variable so to make the following statement work

    android:visiblity='@={isShow? View.VISIBLE : View.GONE}
    

    You need to remove ternary operator, for example:

    android:text="@={model.name}"
    

    Or

    android:checked="@={viewmodel.rememberMe}"
    

    For detail study https://developer.android.com/topic/libraries/data-binding/two-way