我可以找到很多关于如何在BaseAdapter类中使用ArrayList来填充GridView的例子,但我遇到了困难 传递正确的值。当我只是使用光标位置时,这工作正常,但我需要使用 现在是ArrayList。据我所知,解决方案在于正确填充getItem和getItemID。哪里出错 - 有人可以帮忙吗?相关代码如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
allImages = Images.Media.EXTERNAL_CONTENT_URI;
ArrayList<String> imageCollection = new ArrayList<String>();
String[] projection = {
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA
};
getCursor = getContentResolver().query(
allImages,
projection,
null,
null,
null
);
columnIndex = getCursor.getColumnIndexOrThrow(projection[0]); //-- ID number.
arrayIndex = getCursor.getColumnIndexOrThrow(projection[1]); //-- Filepath.
imageCollection.add(String.valueOf(columnIndex));
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this, imageCollection));
} //---End of OnCreate --
public class ImageAdapter extends BaseAdapter {
private Context context;
private int colCount;
private ArrayList<String> tempCollection;
public ImageAdapter(Context c, ArrayList<String> anyCollection) {
context = c;
tempCollection = anyCollection;
colCount = tempCollection.size();
}
//---Returns the number of images---
public int getCount() {
return colCount;
}
//---Returns the item---
public Object getItem(int position) {
return tempCollection.get(position);
}
//---Returns the ID of one item.
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { //---If it's not recycled, initialize some attributes --
imageView = new ImageView(context);
} else {
imageView = (ImageView) convertView;
}
String imageID = String.valueOf(position); //--- FAILS: always 0, causing FileNotFound Exception below.!!!
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5,5,5,5);
imageView.setCropToPadding(true);
imageView.setImageURI( //--- Now create each individual display image --
Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageID)
);
return imageView;
} //---End of ImageAdapter class--
答案 0 :(得分:0)
在活动中,使用下面的代码将ImageId保存到ArrayList。
if (getCursor != null) {
while (getCursor.moveToNext()) {
columnIndex = getCursor.getColumnIndexOrThrow(projection[0]);
imageCollection.add(String.valueOf(getCursor.getLong(columnIndex));
}
}
在ImageAdapter中,使用getView方法,使用以下代码获取ImageId:
String imageID = tempCollection.get(position);