数据绑定适配器。如何获取视图的 ID 引用?

6
我希望将视图引用指定为ImageView的属性。
@BindingAdapter(value = {"imageUrl", "progressView"}, requireAll = false)
public static void setImageUrl(ImageView imageView, String url, @IdRes int progressBar) {
    Context context = imageView.getContext();
    View progressView  = imageView.getRootView().findViewById(progressBar);
     progressView.setVisibility(View.VISIBLE);

    Glide.with(context).load(url).listener(new RequestListener<String, GlideDrawable>() {
        @Override
        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
            if (progressView!= null) {
                 progressView.setVisibility.setVisibility(View.GONE);
            }
            return false;
        }

        @Override
        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
            if (progressView!= null) {
                 progressView.setVisibility(View.GONE);
            }
            return false;
        }
    }).crossFade().into(imageView);
}

然而我的进度视图为空。 我尝试将上下文转换为活动(Activity),并使用findViewById,但结果仍为空。 另一个解决方案是在图片下方添加进度视图,在图片成功加载后应该覆盖它。
3个回答

13

奇怪的是你看到了一个空的progressView。也许你的布局中没有它?

无论如何,你可以尝试这个方法:

<ProgressBar android:id="@+id/progressBarView" .../>
<!-- other stuff -->
<ImageView app:progressView="@{progressBarView}" app:imageUrl="..." .../>

并且在你的BindingAdapter中:

@BindingAdapter(value = {"imageUrl", "progressView"}, requireAll = false)
public static void setImageUrl(ImageView imageView, String url, ProgressBar progressBar) {
    ...
}

2
这是一个很好的答案。我在使用progress_bar_view作为id并尝试将其放入app:progressView时遇到了问题,但当数据绑定发生时,id会变成驼峰式大小写。 - Carson J.

0

@BindingAdapter "value" 是一个字符串数组,所以请尝试这样做:

@BindingAdapter(value = {"imageUrl", "progressViewId"}, requireAll = false)
public static void setImageUrl(ImageView imageView, String iamgeUrl, String progressViewStrId) {
     int progressBarId = Integer.valueOf(progressViewStrId);
     ...
}

0
在我的示例中,我将ScrollView ID作为BindingAdapter的参数传递。
这是布局代码:
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    app:fadeVisible="@{viewModel.shippingMethodsVisible}"
    app:fadeScrollView="@{scrollView}">

这是用 Kotlin 编写的绑定适配器代码:

@JvmStatic @BindingAdapter(value = ["fadeVisible", "fadeScrollView"], requireAll = false)
fun setFadeVisible(view: View, visible: Boolean, scrollView: ScrollView) {
...

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