Android DataBinding 自定义绑定适配器警告

Android DataBinding Custom Binding Adapter Warning

我按照 自定义绑定适配器 的数据绑定文档从官方 Android 开发者网站获取 图像加载 http://developer.android.com/tools/data-binding/guide.html

成功编译代码后,我收到一条警告:

Warning:Application namespace for attribute bind:imageUrl will be ignored.

我的代码如下:

@BindingAdapter({"bind:imageUrl"})
    public static void loadImage(final ImageView imageView, String url) {
        imageView.setImageResource(R.drawable.ic_launcher);
        AppController.getUniversalImageLoaderInstance().displayImage(url, imageView);
    }

为什么会产生这个警告?

还附上截图...

我相信 BindingAdapter 注释中确实忽略了名称空间。如果您使用任何命名空间前缀,无论它是否与您的布局中使用的前缀匹配,都会出现警告。如果省略命名空间,如下所示:

@BindingAdapter({"imageUrl"})

...没有出现警告。

我怀疑警告的存在是为了提醒我们在字符串用作注释实现中的键之前命名空间被剥离。当您考虑布局可以自由声明他们想要的任何名称空间时,这是有道理的,例如app:bind:foo:,注释需要适用于所有这些情况。

试试这个,为我工作!。我希望这可以帮助你。无需绑定适配器即可更改图像资源的简单方法。

<ImageButton
        ...
        android:id="@+id/btnClick"
        android:onClick="@{viewModel::onClickImageButton}"
        android:src="@{viewModel.imageButton}" />

和查看模型Class:

public ObservableField<Drawable> imageButton;
private Context context;

//Constructor
public MainVM(Context context) {
    this.context = context;
    imageButton = new ObservableField<>();
    setImageButton(R.mipmap.image_default); //set image default
}

public void onClickImageButton(View view) {
    setImageButton(R.mipmap.image_change); //change image
}

private void setImageButton(@DrawableRes int resId){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        imageButton.set(context.getDrawable(resId));
    }else{
        imageButton.set(context.getResources().getDrawable(resId));
    }
}

其实还是有一些教程给BindingAdapter注解加上前缀。

使用不带任何前缀的@BindingAdapter({"imageUrl"})

<ImageView
    imageUrl="@{url}"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

专业提示

BindingAdapter 中使用 android: 前缀时不会收到警告。因为那是被鼓励的。 我建议使用 @BindingAdapter("android:src") 而不是创建新属性。

@BindingAdapter("android:src")
public static void setImageDrawable(ImageView view, Drawable drawable) {
    view.setImageDrawable(drawable);
}

@BindingAdapter("android:src")
public static void setImageFromUrl(ImageView view, String url) {
   // load image by glide, piccaso, that you use.
}

仅在需要时创建新属性。