我遇到了问题,希望您能就如何改进我的代码向我提出建议。我正在编写关于将URL中的图像显示到listview的编码,但它没有出现。这是我的代码:
public class MainActivity extends ListActivity {
private String[] imgNames;
private String[] imgUrls;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
String[] imgNames = {"ToDo","Gmail","LinkedIn","Facebook","Google Play"};
this.imgNames = imgNames;
String[] imgUrls = {
"http://ww1.prweb.com/prfiles/2010/05/11/1751474/gI_TodoforiPadAppIcon512.png.jpg",
"http://cdn4.iosnoops.com/wp-content/uploads/2011/08/Icon-Gmail_large-250x250.png",
"http://kelpbeds.files.wordpress.com/2012/02/lens17430451_1294953222linkedin-icon.jpg?w=450",
"http://snapknot.com/blog/wp-content/uploads/2010/03/facebook-icon-copy.jpg",
"https://lh3.googleusercontent.com/-ycDGy_fZVZc/AAAAAAAAAAI/AAAAAAAAAAc/Q0MmjxPCOzk/s250-c-k/photo.jpg"
};
this.imgUrls = imgUrls;
ListAdapter adapter = new ListAdapter(this, imgNames, imgUrls);
setListAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
public class ListAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] imgUrls;
private final String[] imgNames;
public ListAdapter(Context context, String[] imgNames, String[] imgUrls) {
super(context, R.layout.activity_main, imgNames);
this.imgNames = imgNames;
this.imgUrls = imgUrls;
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE);
View row = (View)inflater.inflate(R.layout.activity_main, parent, false);
TextView name = (TextView)row.findViewById(R.id.TextView);
new DownloadImageTask((ImageView) findViewById(R.id.ImageView)).execute(imgUrls[position]);
name.setText(imgNames[position]);
return row;
}
}
}
您对如何改进我的代码有任何建议吗?我尝试使用没有列表视图的代码,但它很有用,但遗憾的是它不适用于listviews。
答案 0 :(得分:14)
请勿使用异步任务执行此操作。使用经过良好测试的图像加载器库。
我建议https://github.com/koush/UrlImageViewHelper
我在三个高调的应用程序中使用了这个库,它为50万用户提供了极好的工作。
然后在你的getView方法中执行此操作
UrlImageViewHelper.setUrlDrawable((ImageView) findViewById(R.id.ImageView), imgUrls[position]);