0
我可以找到很多关于如何在BaseAdapter类中使用ArrayList来填充GridView的示例,但我很难通过 传递正确的值。这在我刚使用光标位置时工作正常,但我现在需要使用ArrayList。据我所知,解决方案在于正确填充getItem和getItemID。哪里有错误 - 有人可以帮忙吗?相关代码如下:从适配器提取ArrayList值到GridView
@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--
在原来的职位,我认为ArrayList中被完全填充_before_试图提取图像标识;并且仍然不清楚,所以在GetView类中没有cursor.moveToPosition指令是正确的。很抱歉,但可以在任何地方找到任何文档。上面的代码看起来很有希望,现在就试试吧。 – Archdeacon 2015-02-06 13:32:57