Reputation: 3190
I have two groups defined inside a ConstraintLayout in my layout. I want them to have visibility opposite to each other. So if group1 is visible then group2 should be gone and vice versa. I am trying to use data binding to achieve this.
<data>
<import type="android.view.View" />
</data>
<android.support.constraint.Group
android:id="@+id/group1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
app:constraint_referenced_ids="..." />
<android.support.constraint.Group
android:id="@+id/group2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="@{group1.visibility == View.VISIBLE? View.GONE : View.VISIBLE}"
app:constraint_referenced_ids="..." />
But I am getting a compilation error that says:
****/ data binding error ****msg:Could not resolve the two-way binding attribute 'visibility' on type 'android.support.constraint.Group'
What am I doing wrong?
Upvotes: 8
Views: 2568
Reputation: 5421
<android.support.constraint.Group
android:id="@+id/group1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="@{viewmodel.shouldShow ? View.VISIBLE : View.GONE }"
app:constraint_referenced_ids="..." />
<android.support.constraint.Group
android:id="@+id/group2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="@{group1.visibility == View.VISIBLE ? View.GONE : View.VISIBLE}"
app:constraint_referenced_ids="..." />
This works because the engine doesn't actually bind one View's visibility to another View's visibility. It notices that both bindings ultimately resolve to the same, bindable source: property of the viewModel - and generates another binding to the same source. It's merely a syntactic sugar (possibly that's why it depends on details that shouldn't matter, like the order of views in XML). I think it was meant to cut down on repetition and nothing more.
Actual binding to another View's property is possible where the property has all the piping for two-way databinding. Like EditText.text
or CheckBox.checked
. In those cases you get actual View-to-View binding.
Upvotes: 0
Reputation: 20926
The problem is that android:visibility
doesn't support two-way data binding. There is no event to notify when the visibility changes, so there is no way to notify when the property should update.
Upvotes: 2
Reputation: 472
I don't know why that error is happening, but this worked for me:
group1.getVisibility() == View.VISIBLE
With that said, I couldn't get the constraint.Group
to work as advertised. Also, to make them opposite each other, presumably you would need similar logic in group1
's visibility, but that would be circular. Why not bind these to a ViewModel that controls when each should be visible?
Upvotes: 6