我正在构建一个应用程序,它从 url 读取图像,然后将它们放入带有一些文本的列表视图中,我创建了自定义适配器布局和所有内容,它可以正常工作,它将所有内容都放入列表视图中,但是当我向下滚动时它滞后很多,任何想法如何摆脱滞后?
这是我的 ArrayAdapter 代码:
public class PhotoAdapter extends ArrayAdapter<PhotoInst> {
private Context con;
private ArrayList<PhotoInst> photos;
private int resource;
public PhotoAdapter(Context context, int textViewResourceId,
ArrayList<PhotoInst> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
con = context;
resource = textViewResourceId;
photos = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView =convertView;
if (rowView==null) {
LayoutInflater inflater = (LayoutInflater) con
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(resource, parent, false);
}
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView1);
TextView textView = (TextView) rowView.findViewById(R.id.textView1);
TextView caption = (TextView) rowView.findViewById(R.id.textView2);
String url = photos.get(position).getPicUrl();
String name = photos.get(position).getName();
String captionText = photos.get(position).getCaption();
Bitmap myPic = DownloadImage(url);
imageView.setImageBitmap(myPic);
textView.setText(name);
caption.setText(captionText);
return rowView;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
}