【问题标题】:How do I access an instance variable inside a BindingAdapter when using Android Data Binding?使用 Android 数据绑定时如何访问 BindingAdapter 中的实例变量?
【发布时间】:2015-11-24 21:49:26
【问题描述】:

所以我使用这个流行的数据绑定代码 sn-p 通过传入 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 设为非静态,则会引发错误:

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.

【问题讨论】:

标签: android static-methods android-databinding


【解决方案1】:

通过自定义投标适配器放置整个电影实例:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 2012-03-22
    • 2015-12-17
    • 2017-10-08
    • 1970-01-01
    • 2021-04-21
    相关资源
    最近更新 更多