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

时间:2018-01-02 22:00:09

标签: android xml mvvm data-binding android-binding-adapter

我想将视图引用指定为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也为null 另一个解决方案是在Image下面添加进度视图,当它成功加载时,它应该覆盖bt image

3 个答案:

答案 0 :(得分:1)

很奇怪您正在看到null 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) {
    ...
}

答案 1 :(得分:0)

@BindingAdapter&#34; value&#34;是一个字符串数组,所以试试这个:

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

答案 2 :(得分: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编写的Bindig Adapters代码:

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