Change ImageView in a GridView Programmatically

痞子三分冷 提交于 2019-12-01 12:07:17

In your adapter:

public void updateImage(int position, int resourceId)
{
    mThumbIds[position] = resourceId;
    notifyDataSetChanged();
}

In your activity:

mAdapter.updateImage(<position>, <image_resource_id>);

Notes

  1. You will have to make the adapter a member of your activity
  2. The main idea is that you modify the backing data and and notify the GridView that this has changed and it is time to be redrawn
  3. Your getView() method implementation needs a lot of improvement. It will cause lots of bugs once the system starts recycling the views (the convertView parameter comes in != null for a position different than it was used for last time)

Here's a sketch of how your getView() should look like:

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    ViewHolder viewHolder;
    LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.image, parent, false);
        // next three lines would not be necessary if:
        //  a) it is the same for every item;
        //  b) you inflate properly (using the parent);
        //  c) you specify this in the item's xml (R.layout.image)
        convertView.setLayoutParams(new GridView.LayoutParams(150, 150));
        convertView.setPadding(8, 8, 8, 8);
        convertView.setBackgroundResource(android.R.color.holo_red_light);

        viewHolder = new ViewHolder();
        viewHolder.mTextView = (TextView)convertView.findViewById(R.id.mastery_text);
        viewHolder.mImageView = (ImageView)convertView.findViewById(R.id.mastery_image);
        // this could also be set in xml perhaps
        viewHolder.mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder)convertView.getTag();
    }

    // update the values every time we are being asked to update the item,
    // because the item might have been reused from a different position
    viewHolder.mImageView.setImageResource(mThumbIds[position]);
    //viewHolder.mTextView.setText("myText");

    return convertView;
}


public static class ViewHolder
{
    TextView mTextView;
    ImageView mImageView;
}
George

You can set a unique id to each ImageView using names (See here) or even integer numbers with a sequence or something (increasing at each image you put in the view).

Another good way to do this is using the tags, with setTag() and getTag(). This question has a good answer: What is the main purpose of setTag() getTag() methods of View?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!