I have created a blinding adapter:
@BindingAdapter("android:profileImage")
fun setProfileImage(imageView: ImageView, profileImage: String) {
Glide.with(imageView.context).load(profileImage)
.placeholder(R.drawable.placeholder)
.into(imageView)
}
And it woks fine. However, when I request the users from a public API, there are some cases in which the profileImage
is null. My goal is to use Glide when the profileImage
is not null, otherwise use the placeholder that exists in the drawable directory. This what I have tried to my ImageVIew:
android:profileImage="@{user.isProfilePictureNotNull() ? user.profileImage : @drawable.placeholder}"
Where isProfilePictureNotNull()
is defined as:
fun isProfilePictureNotNull() = profileImage != null
But Android Studio is complaning with:
'!=', '%', '*', ' ', '-', '/', ':', <, <<, <=, '==', '>', '>=', '>>', '>>>' or '[' expected, got ':'.
How to solve this issue?
CodePudding user response:
The issue here is that you're attempting to pass something which is not a String (@drawable.placeholder
) to your binding adapter. If you replace it with a String, you will see that the error resolves.
My advice would be instead of doing the logic outside of the binding adapter, why not do it inside? Something like this:
@BindingAdapter("android:profileImage")
fun setProfileImage(imageView: ImageView, profileImage: String?) {
if (profileImage != null) {
Glide.with(imageView.context).load(profileImage)
.placeholder(R.drawable.placeholder)
.into(imageView)
} else {
imageView.setImageDrawable(R.drawable.placeholder)
}
}
Now, your XML declaration can simply be:
android:profileImage="@{user.profileImage}"
Additionally, Glide has a .error()
call you can put onto the builder. I am not certain if it works with null or what triggers it, but you could give it a shot. It would look something like this, then:
@BindingAdapter("android:profileImage")
fun setProfileImage(imageView: ImageView, profileImage: String?) {
Glide.with(imageView.context).load(profileImage)
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(imageView)
}