I started with Google’s sample code for a Grid View but how would I choose which images show up? Say one time I just wanted eq1 and eq4 to show up, but another time I wanted eq3, eq 6, and eq12 to show up, what do I need to do to the code? The Integer array contains some integers from another part of the app that won’t be the same all the time, and I’m trying to get those to correspond with which images are in the Grid.
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private int length;
private Integer[] choices;
public ImageAdapter(Context c, int inLength, Integer[] inChoices) {
mContext = c;
length = inLength;
choices = inChoices;
}
public int getCount() {
return 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(200, 50));
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.eq1, R.drawable.eq2,
R.drawable.eq3, R.drawable.eq4,
R.drawable.eq5, R.drawable.eq6,
R.drawable.eq7, R.drawable.eq8,
R.drawable.eq9, R.drawable.eq10,
R.drawable.eq11, R.drawable.eq12,
R.drawable.eq13, R.drawable.eq14,
R.drawable.eq15, R.drawable.eq16,
R.drawable.eq17, R.drawable.eq18,
R.drawable.eq19, R.drawable.eq20,
R.drawable.eq21, R.drawable.eq22
};
}
The way this works is that the view calls
ImageAdapter.getCountto determine how many images should be displayed, and then it callsImageAdapter.getViewfor each position (0, 1, …, up togetCount()-1). So if you just want to show eq1 and eq4,getCountshould return 2 and then ingetViewyou’ll have to replace the linewith something that knows which
mThumbIdselements you want. This is really dependent on how you decide which images should be displayed. Often you would just recreatemThumbIdswith just the elements you want, but if you wanted another layer of indirection, you could try something like this:and replace that one line in
getViewwith: