Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data binding adapter. How to get view by id reference?

I want to specify view reference as atribute to 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);
}

however my progress view is null. I tried cast context to activity and findViewById also null Another solution is just add progress view below Image and when it loads successfully it should be overlayed bt image

like image 964
Chickin Nick Avatar asked Jan 02 '18 22:01

Chickin Nick


People also ask

How do I get the context in the Binding adapter?

The value for context is the Context from the root View's getContext(). The context variable will be overridden by an explicit variable declaration with that name. In other words, every time you need to pass the context just use "context" as in @{Object. method(context)} .

How would you enable view Binding for a module in your application so you can reference views from layout files without using Findviewbyid?

To enable view binding, configure viewBinding in your module-level build. gradle file. Once enabled for a project, view binding will generate a binding class for all of your layouts automatically. You don't have to make changes to your XML — it'll automatically work with your existing layouts.


1 Answers

Strange that you're seeing a null progressView. You may not have it in your layout maybe?

In any case, you can do this instead:

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

And in your BindingAdapter:

@BindingAdapter(value = {"imageUrl", "progressView"}, requireAll = false)
public static void setImageUrl(ImageView imageView, String url, ProgressBar progressBar) {
    ...
}
like image 53
George Mount Avatar answered Oct 30 '22 15:10

George Mount