使用 Android 数据绑定时,如何访问 BindingAdapter 内的实例变量? [英] How do I access an instance variable inside a BindingAdapter when using Android Data Binding?

查看:35
本文介绍了使用 Android 数据绑定时,如何访问 BindingAdapter 内的实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使用这个流行的数据绑定代码片段通过传入 URL 将图像加载到列表项的图像视图中:

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}"
        />

绑定适配器:

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.
                });
    }

如果我只是将 BindingAdapter 设为非静态,则会引发错误:

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.

推荐答案

通过自定义的biding Adapter 将整部电影instace:

Put whole movie instace through custom biding adapter:

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

绑定适配器:

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);
             });
     }
}

这篇关于使用 Android 数据绑定时,如何访问 BindingAdapter 内的实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆