gpt4 book ai didi

android - 使 ListView 滚动平滑

转载 作者:行者123 更新时间:2023-11-29 00:36:22 26 4
gpt4 key购买 nike

我正在浏览 Android 开发者网站并阅读一些文章。有一种使用 AsyncTask 延迟加载 ListView 中的图像的方法:

// Using an AsyncTask to load the slow images in a background thread
new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;

@Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
return mFakeImageLoader.getImage();
}

@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (v.position == position) {
// If this item hasn't been recycled already, hide the
// progress and set and show the image
v.progress.setVisibility(View.GONE);
v.icon.setVisibility(View.VISIBLE);
v.icon.setImageBitmap(result);
}
}
}.execute(holder);

但是,对我来说,该代码似乎有点问题。假设我们从 Internet 加载图像,每个图像都需要几秒钟的时间来加载。

作为用户,如果我们滚动列表然后切换到另一个 Activity,将会有一些 AsyncTasks 在后台运行并占用一些带宽,而我们在新的前台 Activity 中可能需要它。

您通常如何使用他们的方法来处理这种情况?回收 View 时,您是否终止了与持有者关联的 AsyncTask?您是否在适配器中跟踪哪些 AsyncTasks 仍在运行并在 Activity 停止时将其全部取消?还有其他方法吗?

我的问题主要是关于架构清理部分以解决该问题(与其说是实现)

最佳答案

我想说的是,大多数情况下下载不会花费足够的时间让这成为一个问题,但如果是,你应该杀死它们。同样在他们的实现中,他们下载图像并检查 View 是否已被重用。如果你有很长的延迟,你应该在重用时取消任务。请注意,任务的执行顺序因 Android 版本而异。来自docs :

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.

关于android - 使 ListView 滚动平滑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12486513/

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