我尝试使用CardView实现RecyclerView,卡片只是带有textview的图像视图。一开始一切都按预期工作,但如果你向下滚动,然后在recyclerView中备份,那么imageViews将为空,textview很好。
发生了什么的GIF
适配器:
public class NewsCardAdapter : RecyclerView.Adapter
{
private List<RSSItem> items;
public NewsCardAdapter()
{
HasStableIds = true;
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
var view = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.NewsItem, parent, false);
NewsViewHolder viewHolder = new NewsViewHolder(view);
return viewHolder;
}
public override long GetItemId(int position)
{
return items[position].Id;
}
public override async void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
{
var item = items[position];
var holder = viewHolder as NewsViewHolder;
if (item.ThumbNail != null)
{
holder.ImgThumbnail.SetImageBitmap(await BitmapFactory.DecodeStreamAsync(item.ThumbNail));
}
else
{
// Place holder in case item doesn't have thumbnail
holder.ImgThumbnail.SetImageResource(Resource.Drawable.Icon);
}
holder.Title.Text = item.Title;
}
public override int ItemCount => items.Count;
public List<RSSItem> Items
{
get { return items; }
set { items = value; }
}
}
public class NewsViewHolder : RecyclerView.ViewHolder
{
private ImageView imgThumbnail;
private TextView title;
public NewsViewHolder(View itemView) : base(itemView)
{
imgThumbnail = itemView.FindViewById<ImageView>(Resource.Id.img_thumbnail);
title = itemView.FindViewById<TextView>(Resource.Id.news_title);
}
public ImageView ImgThumbnail
{
get { return imgThumbnail; }
set { imgThumbnail = value; }
}
public TextView Title
{
get { return title; }
set { title = value; }
}
}
模型(RSSItem):
public class RSSItem : INotifyPropertyChanged
{
[PrimaryKey, AutoIncrement]
public long Id { get; set; }
public string Title { get; set; }
private Stream thumbnail;
[Ignore]
public Stream ThumbNail
{
get { return thumbnail; }
set
{
thumbnail = value;
OnPropertyChanged();
}
}
// ...
}
我的猜测 - 它与将imageView源分配给从流解码的位图而不是在模型中存储位图本身有关。但是我不能这样做,因为System.Drawable不是PCL的一部分。
答案 0 :(得分:1)
尝试将Stream定位为在解码前启动,如Stream.Position = 0; 此外,不确定您的流是什么,您可以使用MemoryStreams在PCL级别缓存图像,或在UI级别缓存图像(通过存储BitmapFactory.DecodeStreamAsync结果)。
答案 1 :(得分:0)
我建议您使用Picasso库来检索图像。它的性能更高(主要是在内存中)并且会解决您的问题。