在小部件中,我有一个标题和图像元素的列表。
当屏幕上出现项目时,图像是从Internet下载的。
如果我直接通过“ getViewAt”方法下载图像,则可以正常工作:图像已正确加载,但可视化出现了延迟。
因此,我尝试异步加载图像,但是它不起作用:图像被随机放置,并且某些元素重复出现。
怎么了?
代码如下:
class WidgetViewsFactory implements RemoteViewsService.RemoteViewsFactory {
private List<News> mNewsItems = new ArrayList<>();
private final Context mContext;
...
public RemoteViews getViewAt(int position) {
RemoteViews widgetRow = new RemoteViews(mContext.getPackageName(), R.layout.widget_news_item);
new AsyncCaller(widgetRow).execute(mNewsItems.get(position).getImageUrl);
widgetRow.setTextViewText(R.id.widget_title, mNewsItems.get(position).getTitle();
return widgetRow;
}
private class AsyncCaller extends AsyncTask<String, Void, Bitmap> {
RemoteViews widgetRow;
AsyncCaller(RemoteViews widgetRow){
this.widgetRow = widgetRow;
}
@Override
protected Bitmap doInBackground(String... url) {
try {
URL imgurl = new URL(url[0]);
Bitmap bitmap = BitmapFactory.decodeStream(imgurl.openConnection().getInputStream());
return bitmap;
} catch (Exception e) {
return null;
}
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
this.widgetRow.setImageViewBitmap(R.id.wiget_image, bitmap);
}
super.onPostExecute(bitmap);
}
}
}