1

Is it possible to show / hide views depending on values from same XML?

I don't want to write many conditions to java file.

What I mean is; if we can do this

  <TextView android:text="@{user.lastName}"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:visibility="@{user.isAdult ? View.VISIBLE : View.GONE}"/>

We should be able to do this too right?

 android:visibility="@{idOfMySwitch.isSelected() ? View.VISIBLE : View.GONE}"/>

If so how can I do it?

tynn
  • 38,113
  • 8
  • 108
  • 143
Mohamed
  • 1,251
  • 3
  • 15
  • 36

2 Answers2

0

You should be checking the state of the view model to determine whether or not to show the element.

In your ViewModel:

@Bindable
public boolean isAdult() {
    return isAdult;
}

In your activity, you should have an on click listener on the switch which updates isAdult on the ViewModel accordingly, which will in turn update the visibility of your textview.

You can see a similar example here.

Community
  • 1
  • 1
Stuart Simmons
  • 308
  • 3
  • 7
0

You cannot do this. idOfMySwitch.isSelected() is not observable for the data binding itself.

For such cases I have a holder and assign it as a 2-way binding to the switch and one way to the visibility.

For selection you might run into issues though. 2-way binding is not, or at least not easily implementable. But with a switch you might want to use the checked state anyway.

<Switch ...
    android:checked="@={holder.myState}" />
<TextView ...
    android:visibility="@{holder.myState ? View.VISIBLE : View.GONE}" />
tynn
  • 38,113
  • 8
  • 108
  • 143