Create a new class (nested or otherwise), called ImageAdapter, which extends BaseAdapter:
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 our 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
};
}
First we take care of some required methods inherited from BaseAdapter.
The constructor and getCount()
are self-explanitory. Normally, getItem()
should return the actual object at the specified position in our Adapter, but for this Hello World,
we're not going to bother. Likewise, getItemId()
should return the row id of
the item, but right now we don't care.
However, getView()
is the method we care about. This one creates a new View for each image that we
put in our ImageAdapter. So we're going to create an ImageView each time. When this is called, we're
going to receive a View, which is likely a recycled View object (at least after the first call), so we
check for this—if it's null, we initialize the ImageView and setup all the properties we want.
The LayoutParams()
initialization sets the height and width of the View—this ensures
that no matter the drawable size, each image is resized and cropped to fit in the ImageView (if necessary).
With setScaleType()
, we say that images should be cropped toward the center (if necessary).
And finally, we set the padding within the ImageView. (Note that, if the images have various aspect-ratios,
as they do in this demo, then less padding will cause for more cropping of the image, if it does not match
the dimensions given to the ImageView.) At the end of getView()
we set the image resource and
return the ImageView.
All that's left is our array or drawable resources at the bottom.