Am an Android newbiew. Am trying to load a bunch of images in my res/Drawable folder into a Gridview via an array adapter. unfortunately my the app crashes each time i try to vi
The specific answer to your issue is your constructor for your adapter is:
(this,R.layout.grid_view_row,R.id.imageGrid , planets);
R.layout.grid_view_row needs to be an xml file with only a TextView. It can't be wrapped in anything else like a LinearLayout or RelativeLayout. So you would need:
However, If you want to load images into a GridView I would recommend using an "image adapter" that extends BaseAdapter and then get the images from there. Very similar to this example:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
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(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize 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]);
return imageView;
}
// references to your images
private Integer[] mThumbIds = {
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7
};
}
where getView sets how the grid should look and mThumbIds is an Array of every picture that you want. From here in the Activity that you want to display the GridView in just add the code:
gridview.setAdapter(new ImageAdapter(this));