因此,我使用此流行的数据绑定(bind)代码段通过传入URL将图像加载到列表项的imageview中:
<ImageView
android:layout_width="match_parent"
android:layout_height="150dp""
app:imageUrl="@{movie.imageUrl}"
/>
绑定(bind)适配器:
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.
最佳答案
通过自定义绑定(bind)适配器放置整个影片实例:
<ImageView
android:layout_width="match_parent"
android:layout_height="150dp""
app:movie="@{movie}"
/>
绑定(bind)适配器: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);
});
}
}