问题
I'm trying to set the visibility
and the src
of an ImageView
using data binding. I don't know why this error is showing up, and I truely believe that this was working at one point, but I could be wrong.
Layout:
<data>
<import type="android.view.View" />
<import type="android.support.v4.content.ContextCompat" />
<variable
name="viewData"
type="com.myapp.SomethingViewData" />
</data>
...
<ImageView
...
android:src="@{ContextCompat.getDrawable(context, viewData.getIconResource())}"
android:visibility="@{viewData.getIconVisibility() ? View.VISIBLE : View.GONE}" />
Data class
@Parcelize
data class SomethingViewData(val iconResource: Int,
val iconVisibility: Boolean) : Parcelable
Error message:
error: '@{ContextCompat.getDrawable(context, viewData.getIconResource())}' is incompatible with attribute android:src (attr) reference|color.
error: '@{viewData.getIconVisibility() ? View.VISIBLE : View.GONE}' is incompatible with attribute android:visibility (attr) enum [gone=2, invisible=1, visible=0].
What does this mean and how do I fix it?
回答1:
In my case a missing closing brace caused this error to pop up for me - I had:
android:visibility="@{moment.state == State.COMPLETE ? View.GONE : View.VISIBLE"
instead of:
android:visibility="@{moment.state == State.COMPLETE ? View.GONE : View.VISIBLE}"
回答2:
Wow, so, somehow dataBinding { enabled = true }
was removed from my app modules build.gradle file. Adding it back and everything worked like before.
回答3:
Your "getIconVisibility" return an integer but android:visibility
(in your XML file) need a enum value: Visibility.Gone | Visibility.Visible | Visibility.Invisible
回答4:
Try using single quotations in your
src
andvisibility
android:src='@{ContextCompat.getDrawable(context, viewData.getIconResource())}'
android:visibility='@{viewData.getIconVisibility() ? View.VISIBLE : View.GONE}'
来源:https://stackoverflow.com/questions/53202846/viewbinding-with-error-incompatible-with-attribute-androidvisibility