0

I have set up a GridView following the guideline here. Now I want to programmatically change one of the images (user does not click the image to change it). How do I do that if I know the position of the image in the grid?

Jeff
  • 67
  • 1
  • 9

1 Answers1

1

Off of the top of my head, you could create objects that your adapter displays with. Have your getView() method set the ImageView reference inside that object.

Once you have that complete, you could use the getItem() method to return that object, get your reference to the ImageView and then set the image programmatically.

If you're using that exact implementation from that guide, you could use an ArrayList.

public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<ImageView> mImageViewArrayList = new ArrayList<>(mThumbIds.length);

public ImageAdapter(Context c) {
    mContext = c;
} 

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

public ImageView getItem(int position) {
    return mImageViewArrayList.get(position); 
} 

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;
    } 

    mImageViewArrayList.set(position,imageView);

    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
}; 
} 

Then in your class where you want to change it programmatically do this.

private void setImage(int position, int image){
    mAdapter.getItem(position).setImageResource(image);
}
Nick H
  • 8,897
  • 9
  • 41
  • 64