我有一个已解析的列表视图。元素的数量不固定。 当我单击列表视图的项目时,它会根据需要在其他活动上显示相应的文件。 到目前为止,这一切都正如我所愿。 现在我想在每个List项目上显示缩略图。每次单击时打开的文件都是“.png”文件,我想在列表中将png显示为缩略图(每个项目都有相应的缩略图) 我怎样才能做到这一点??我是android的新手,所以plz给我代码示例求助。 我已经做了很多搜索和阅读懒惰加载的东西,但它对我来说非常复杂。 在此先感谢您的帮助!!
答案 0 :(得分:2)
您需要扩展listview的适配器,然后在适配器的getView()方法中指定自定义布局。
private class MyAdapter extends ArrayAdapter</*params*/> {
private ArrayList</*params*/> items;
//you will a reference to a context in getView()
private Context ctx;
public MyAdapter(Context context, int resourceId, ArrayList</*params*/> items) {
super(context, resourceId, items);
this.items = items;
this.ctx = context;
}
//here is where you can create a custom view for each list item
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.my_custom_view, null);
//Your custom view will contain an ImageView
//which you can assign the thumbnail to.
ImageView image = (ImageView)convertView.findViewById(R.id.my_custom_view_thumbnail);
//set the thumbnail from a drawable resource
new GetImage("http://www.example.com").execute(image);
}
return v;
}
}
下载图片
public class GetImage extends AsyncTask<ImageView, Void, ImageView> {
String url = null;
Bitmap thumbnail = null;
public GetImage(String url){
this.url = url;
}
@Override
protected void onPreExecute() {
}
@Override
protected ImageView doInBackground(ImageView... params) {
try {
thumbnail = BitmapFactory.decodeStream((InputStream) new URL(url).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return params[0];
}
@Override
public void onPostExecute(ImageView result) {
result.setImageBitmap(thumbnail);
}
}
答案 1 :(得分:2)
最好的办法是制作一个自定义列表视图行,它可以有一个图像视图,您可以在其中显示图像。
以下是一些可以帮助您的教程列表 Custom List View tutorial 1 Custom list view tutorial2