Android DataBinding 资源数据绑定

3 篇文章 0 订阅
2 篇文章 0 订阅
<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>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值