我有一个 ListView ,我正在其中从用户的 SD 卡加载所有图像(作为预览)。我有一个自定义的 SimpleCursorAdapter,当我覆盖 getView() 方法时,我尝试启动后台线程来加载图像。
我想做的基本上是使用后台线程或其他方式将图像预览“延迟加载”到 ListView 中。我愿意接受新的解决方案。主要问题是滚动非常慢,因为加载图像是一项非常昂贵的操作。
这是我正在尝试的相关代码:
public class listOfImages extends SimpleCursorAdapter {
private Cursor c;
private Context context;
public listOfImages(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.c = c;
this.context = context;
}
public View getView(int pos, View inView, ViewGroup parent) {
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.image_item, null);
}
this.c.moveToPosition(pos);
int columnIndex = this.c.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);
String name = this.c.getString(columnIndex);
columnIndex = this.c.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE);
String size = this.c.getString(columnIndex);
columnIndex = this.c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
String data = this.c.getString(columnIndex); //gives the filename
TextView sTitle = (TextView) v.findViewById(R.id.image_title);
sTitle.setText(name);
imagePreviewLoader ipl = new imagePreviewLoader(v, data);
ipl.mainProcessing();
v.setTag(data);
v.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "Image: " + v.getTag(), Toast.LENGTH_SHORT).show();
String filename = (String) v.getTag();
Intent intent = new Intent(context, ViewImage.class);
intent.putExtra("filename", filename);
context.startActivity(intent);
}
});
return v;
}
现在我正在尝试的后台线程:
public class imagePreviewLoader {
private Handler handler = new Handler();
private View v;
private String data;
public imagePreviewLoader(View v, String data) {
this.v = v;
this.data = data;
}
protected void mainProcessing() {
Thread thread = new Thread(null, doBackground, "Background");
thread.start();
}
private Runnable doBackground = new Runnable() {
public void run() {
backgroundThreadProcessing();
}
};
private void backgroundThreadProcessing() {
handler.post(doUpdateGUI);
}
private Runnable doUpdateGUI = new Runnable() {
public void run() {
updateGUI();
}
};
private void updateGUI() {
ImageView img = (ImageView) v.findViewById(R.id.image_view);
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inSampleSize = 30;
bfo.inTargetDensity = 50;
Bitmap bm = BitmapFactory.decodeFile(data, bfo);
img.setImageBitmap(bm);
}
问题是当您滚动时,所有内容都会尝试立即加载,因此滚动速度非常慢。我认为会发生什么是 imageview 将保持空白(或占位符),直到线程加载了适当的图像。我想不是。
感谢您的帮助。
最佳答案
看看我对 this 的回答问题,它有一个示例项目,展示了如何从网上下载图像。您应该能够很容易地修改它,以便从 SD 卡获取图像。
关于java - Android 将图像异步加载到 ListView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6683741/