android 数据绑定适配器,如何通过id引用获取视图?

eufgjt7s  于 2023-06-28  发布在  Android
关注(0)|答案(3)|浏览(119)

我想将视图引用指定为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);
}

但是我进度视图为空。我试着将上下文转换为活动,findViewById也为空另一种解决方案是在图像下面添加进度视图,当它成功加载时,它应该被覆盖在图像上

7vux5j2d

7vux5j2d1#

奇怪的是,你看到一个空的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) {
    ...
}
hl0ma9xz

hl0ma9xz2#

@BindingAdapter“value”是一个字符串数组,所以试试这个:

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

gzszwxb43#

在我的示例中,我传递了一个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编写的Bindig Adapters代码:

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

相关问题