我正在尝试将包含图像源url字符串的数组发送到网格视图的imageadapter。但只有数组的最后一个url用于在适配器中设置图像。这里的一些帮助将不胜感激。
GridView gridview = (GridView) findViewById(R.id.gridview);
ImageAdapter imageListAdapter = null;
for( int inx = 0 ; inx < imageUrl.length ; inx++)
{
imageListAdapter = new ImageAdapter(context,imageUrl[inx],productName[inx] );
System.out.println(imageUrl[inx]);
System.out.println(productName[inx]);
gridview.setAdapter(imageListAdapter);
}
适配器代码:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
static int i = 0;
String url = null;
String name = null;
public ImageAdapter(Context c, String url , String name ) {
mContext = c;
this.url = url;
this.name = name;
}
public int getCount() {
// return url.length;
return ++i;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialise some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8,8,8,8);
} else {
imageView = (ImageView) convertView;
}
//imageView.setImageResource(mThumbIds[position]);
//Bitmap bmp = loadBitmap("http://www.xvr.com/aero/planes/boeing/boeingf15.jpg");
Bitmap bmp = loadBitmap(url);
System.out.println("in adapter :"+url);
//imageView.setImageResource(mThumbIds[position]);
imageView.setImageBitmap(bmp);
return imageView;
}
public static Bitmap loadBitmap(String url)
{
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), 4 * 1024);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, 4 * 1024);
int byte_;
while ((byte_ = in.read()) != -1)
out.write(byte_);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e("","Could not load Bitmap from: " + url);
} finally {
try{
in.close();
out.close();
}catch( IOException e )
{
System.out.println(e);
}
}
return bitmap;
}
}
答案 0 :(得分:1)
这是因为您每次都在for循环中创建新的ImageAdapter并将其设置为Gridview,因此在循环的最后一次迭代中,最后一个映像设置为adapter,最后该适配器设置为gridview。
注意:您的实施有误,请查看以下示例http://mobiforge.com/designing/story/understanding-user-interface-android-part-3-more-views并搜索关键字GridView
将url和name作为字符串数组传递一次,而不是每次创建ImageAdapter的新对象,如下所示,并相应地更改适配器代码。
imageListAdapter = new ImageAdapter(context,imageUrl,productName);