Android GridView Adapter

When creating a Adapter for a GridView, like following :

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
}

How does Adapter know how many items it has to display on screen? What if I want several items to display the same picture ? Thanks.

Upvotes: 0

Views: 957

Answers (1)

vipul mittal
vipul mittal

Reputation: 17401

Whatever count the getCount method returns is the number of items adapter is going to display

public int getCount() {
    return mThumbIds.length;
}

If you want several items to display same image create a different array of images, having some repeated images, and return length of that array.

for eg:

// 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_5, R.drawable.sample_5
        R.drawable.sample_6, R.drawable.sample_7,
        R.drawable.sample_7, R.drawable.sample_7
}

Upvotes: 1

Related Questions