我的应用程序从网络服务获取文章并显示其标题、图片和其他字段。为了显示图片,我使用Picasso。
问题 - 在滚动RecyclerView时,我发现图片位置错乱。有些项具有重复的图像。我知道这是由于RecyclerView重用xml项布局导致的问题。但我认为必须存在解决此问题的方法。我已经在stackoverflow上搜索了一些帖子,但都没有帮助。例如:
Picasso loads pictures to the wrong imageview in a list adapter
我尝试过以下方法,但问题仍然存在:
public class ArticleAdapter extends RecyclerView.Adapter<ArticleAdapter.ArticleViewHolder> {
protected Activity mActivity;
protected List<Article> mItems = new ArrayList<>();
private static OnEntityClickCallback mCallback;
public ArticleAdapter(Activity pActivity) {
mActivity = pActivity;
}
public void setItemClickCallback(OnEntityClickCallback pCallback) {
this.mCallback = pCallback;
}
@Override
public ArticleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View articleView = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_article_item, parent, false);
return new ArticleViewHolder(articleView);
}
public void addItem(List<Article> moreItems) {
mItems.addAll(moreItems);
notifyDataSetChanged();
}
public void removeItems(){
mItems.clear();
notifyDataSetChanged();
}
@Override
public void onBindViewHolder(ArticleViewHolder holder, int position) {
holder.bind(mItems.get(position));
}
@Override
public int getItemCount() {
return mItems.size();
}
static class ArticleViewHolder extends RecyclerView.ViewHolder {
private TextView tvTitle;
TextView tvAuthor;
TextView tvPostdate;
ImageView imgImage;
RatingBar ratingBar;
public ArticleViewHolder(View view) {
super(view);
this.tvTitle = (TextView) view.findViewById(R.id.tv_title);
this.tvAuthor = (TextView) view.findViewById(R.id.tv_author);
this.tvPostdate = (TextView) view.findViewById(R.id.tv_date);
this.imgImage = (ImageView) view.findViewById(R.id.img_image);
this.ratingBar = (RatingBar) view.findViewById(R.id.ratingBar);
}
public void bind(final Article article) {
tvTitle.setText(article.getTitle());
tvPostdate.setText(article.getPostdate());
tvAuthor.setText(article.getAuthor());
// Canceling the older request
Picasso.with(imgImage.getContext()).cancelRequest(imgImage);
// Creating a new request.
if (article.getImage() != null) {
Picasso.with(imgImage.getContext()).load(article.getImageUrl())
.placeholder(R.drawable.noimage)
.error(R.drawable.noimage)
.into(imgImage);
}
this.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mCallback != null)
mCallback.onEntitySelected(article);
}
});
}
}
}
更新 - 我的布局文件的一部分
<ImageView
android:id="@+id/img_image"
android:layout_width="match_parent"
android:layout_height="@dimen/cardview_image_thumbnail_height"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:scaleType="centerCrop"
android:layout_margin="@dimen/cardview_padding_btw_widgets"
android:src="@drawable/noimage"
/>
希望得到任何形式的帮助,感谢。