<ImageView
android:layout_width="match_parent"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:error="@{0}"
app:imageUrl="@{@string/sign_in_bg_image_url}"
app:layout_constraintHeight_default="percent"
app:layout_constraintHeight_percent="0.48"
app:layout_constraintTop_toTopOf="parent"
tools:src="@drawable/bg_tenant" />
/** 为[ImageView]设置网络图片 */
@BindingAdapter(value = ["imageUrl", "placeholder", "error"], requireAll = false)
fun ImageView.loadByUrl(url: String?, placeholder: Drawable? = null, error: Drawable? = null) {
if (url.isNullOrEmpty()) {
setImageDrawable(error)
return
}
context.imageLoader.enqueue(
ImageRequest.Builder(context)
.data(url)
.error(error)
.target(this)
.placeholder(drawable ?: placeholder)
.build()
)
}
@{@string/sign_in_bg_image_url}引用xml中string
@{0} 引用颜色资源
package androidx.databinding.adapters;
import androidx.databinding.BindingConversion;
import android.content.res.ColorStateList;
import android.graphics.drawable.ColorDrawable;
/**
* Build in converters to converts for color.
*/
public class Converters {
/**
* Converts {@code int} color into a {@link ColorDrawable}.
*
* @param color The integer representation of the color.
*
* @return ColorDrawable matching the color
*/
@BindingConversion
public static ColorDrawable convertColorToDrawable(int color) {
return new ColorDrawable(color);
}
/**
* Converts {@code int} color into a {@link ColorStateList}.
*
* @param color The integer representation of the color.
*
* @return ColorStateList from the single color
*/
@BindingConversion
public static ColorStateList convertColorToColorStateList(int color) {
return ColorStateList.valueOf(color);
}
}
其中@BindingConversion public static ColorDrawable convertColorToDrawable(int color) { return new ColorDrawable(color); }会将颜色值自动转换为Drawable
android:text="@{@string/replace(firstReplace, lastReplace)}"
<string name="replace">replace: %1$s:%2$s</string>