gpt4 book ai didi

android - 如何将我的图像下载器移动到 Android 上的单独线程中?

转载 作者:搜寻专家 更新时间:2023-11-01 07:41:12 25 4
gpt4 key购买 nike

我的 Android 设备上运行了以下代码。它工作得很好,可以很好地显示我的列表项。它也很聪明,因为它只在 ArrayAdapter 需要时才下载数据。但是,在下载缩略图时,整个列表会停止,您无法滚动直到下载完成。有什么方法可以对此进行线程处理,以便它仍然可以愉快地滚动,也许会显示一个用于下载图像的占位符,完成下载,然后显示?

我想我只需要将我的 downloadImage 类放入它自己的线程中,以便它与 UI 分开执行。但是如何将其添加到我的代码中是个谜!

如能提供任何帮助,我们将不胜感激。

private class CatalogAdapter extends ArrayAdapter<SingleQueueResult> {

private ArrayList<SingleQueueResult> items;

//Must research what this actually does!
public CatalogAdapter(Context context, int textViewResourceId, ArrayList<SingleQueueResult> items) {
super(context, textViewResourceId, items);
this.items = items;

}

/** This overrides the getview of the ArrayAdapter. It should send back our new custom rows for the list */
@Override
public View getView(int position, View convertView, ViewGroup parent) {

View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.mylists_rows, null);

}
final SingleQueueResult result = items.get(position);
// Sets the text inside the rows as they are scrolled by!
if (result != null) {

TextView title = (TextView)v.findViewById(R.id.mylist_title);
TextView format = (TextView)v.findViewById(R.id.mylist_format);
title.setText(result.getTitle());
format.setText(result.getThumbnail());

// Download Images
ImageView myImageView = (ImageView)v.findViewById(R.id.mylist_thumbnail);
downloadImage(result.getThumbnail(), myImageView);

}

return v;
}
}

// This should run in a seperate thread
public void downloadImage(String imageUrl, ImageView myImageView) {

try {
url = new URL(imageUrl);
URLConnection conn = url.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
myImageView.setImageBitmap(bm);
} catch (IOException e) {
/* Reset to Default image on any error. */
//this.myImageView.setImageDrawable(getResources().getDrawable(R.drawable.default));
}
}

最佳答案

这是我在我的应用中使用的简化版本:

// this lives in Application subclass and is reused
public static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor();

// the method itself

public void attachImage(final String fileUrl, final ImageView view) {
EXECUTOR.execute(new Runnable() {

@Override
public void run() {
final Drawable image = methodThatGetsTheImage(fileUrl);
if (image != null) {
view.post(new Runnable() {

@Override
public void run() {
view.setImageDrawable(drawable);
}
});
}
}
});
}

关于android - 如何将我的图像下载器移动到 Android 上的单独线程中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2578439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com