Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

static methods - How do I access an instance variable inside a BindingAdapter when using Android Data Binding?

So I'm using this popular data binding code snippet to load in image into imageview of list items by passing in URL:

  <ImageView
        android:layout_width="match_parent"
        android:layout_height="150dp""
        app:imageUrl="@{movie.imageUrl}"
        />

The Binding Adapter:

class Movie{
    boolean isLoaded;

    @BindingAdapter({"bind:imageUrl"})
        public static void loadImage(final ImageView view, String imageUrl) {

            Picasso.with(view.getContext())
                .load(imageUrl)
                .into(view, new Callback.EmptyCallback() {
                @Override public void onSuccess() {
                    //set isLoaded to true for the listview item
                    // but cannot access boolean isLoaded as it is non static.
                });
    }

If I simply make the BindingAdapter non-static then it throws error:

java.lang.IllegalStateException: Required DataBindingComponent is null     in class MovieTileBinding. A BindingAdapter in     com.example.moviesapp.Pojos.Results is not static and requires an object to     use, retrieved from the DataBindingComponent. If you don't use an inflation method taking a DataBindingComponent, use DataBindingUtil.setDefaultComponent or make all BindingAdapter methods static.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Put whole movie instace through custom biding adapter:

 <ImageView
        android:layout_width="match_parent"
        android:layout_height="150dp""
        app:movie="@{movie}"
        />

The Binding Adapter:

class Movie{
boolean isLoaded;

@BindingAdapter({"movie"})
    public static void loadImage(final ImageView view, final Movie movie) {
        if(movie != null &&?moview.getImageUrl() != null){
          Picasso.with(view.getContext())
             .load(movie.getImageUrl())
             .into(view, new Callback.EmptyCallback() {
             @Override public void onSuccess() {
                 image.setLoaded(true);
             });
     }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...