gpt4 book ai didi

java - Android ArrayAdapter 缓慢滚动

转载 作者:行者123 更新时间:2023-12-02 06:44:50 25 4
gpt4 key购买 nike

我正在构建一个应用程序,它从 url 读取图像,然后将它们放入带有一些文本的 ListView 中,我创建了自定义适配器布局和所有内容,并且它有效,它按照想象将所有内容放入 ListView 中,但是当我向下滚动时它滞后很多,有什么想法如何摆脱滞后吗?

这是我的 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;
}

}

最佳答案

您正在主应用程序线程上下载图像。这不仅会显着降低您的 UI 速度,而且您的应用会在 Android 4.0+ 上崩溃并出现 NetworkOnMainThreadException

使用PicassoSmartImageView或者异步下载图像的东西。

关于java - Android ArrayAdapter 缓慢滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18765110/

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