我按照指南here设置了GridView。现在我想以编程方式更改其中一个图像(用户执行不点击图像进行更改)。如果我知道图像在网格中的位置,我该怎么做?
答案 0 :(得分:1)
离开我的头顶,您可以创建适配器显示的对象。让你的getView()方法在该对象中设置ImageView引用。
完成后,可以使用getItem()方法返回该对象,获取对ImageView的引用,然后以编程方式设置图像。
如果您正在使用该指南中的确切实现,则可以使用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
};
}
然后在你想要以编程方式更改它的课程中。
private void setImage(int position, int image){
mAdapter.getItem(position).setImageResource(image);
}