安卓DataBinding自定义绑定适配器警告

77

我遵循了官方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);
    }
为什么会产生这个警告?附有屏幕截图...enter image description here

1
你在布局中是否使用了相同的命名空间 "bind:" - betorcs
3个回答

127

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

@BindingAdapter({"imageUrl"})

我认为这个警告的存在是为了提醒我们,在将字符串用作注释实现中的键之前,该命名空间已被剥离。这在考虑到布局可以声明任何它们想要的命名空间(例如app:bind:foo:)并且注释需要在所有这些情况下工作时就会有意义。

如果没有出现警告,那么我们可能会忽略掉这个剥离步骤,使得对于具有非标准命名空间的布局而言注释无法正常工作。


12
请注意,“android:”命名空间是唯一的例外:如果您为内置属性(例如“android:onClick”)设置“BindingAdapter”,则可以包括前缀,而不会收到任何警告。 - Lorne Laliberte

18

实际上仍然有一些教程会在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.
}

只有在需要时才创建新属性。


2
尝试这个方法,对我起作用了!我希望这能帮助到你。这是一种简单的方法,可以在不使用绑定适配器的情况下更改图片资源。
<ImageButton
        ...
        android:id="@+id/btnClick"
        android:onClick="@{viewModel::onClickImageButton}"
        android:src="@{viewModel.imageButton}" />

视图模型类:

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));
    }
}

ViewModel 不应使用任何 Android 特定的类(尤其是视图),也不应访问上下文,因为这违背了将其放在首位的目的。 - ruX

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接