我希望图片只出现在一个地方。单击另一个单元格时,同一图像将显示在此处,并从之前单击的按钮中消失。
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(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images. Here are 16 for 4x4 grid
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,
};
}
MainActivity.java
public class MainActivity extends Activity {
int i=0;
long firstClick,secondClick;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//no title
requestWindowFeature(Window.FEATURE_NO_TITLE);
// making it full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) v;
imageView.setImageResource(R.drawable.sample_8);
}
});
}
}
答案 0 :(得分:1)
请勿直接修改ImageView
中的GridView
,而是修改适配器中的数据并调用notifyDataSetChanged
。
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
if (lastClicked != -1) {
// we previously selected a position
mThumbs[lastClicked] = R.drawable.default_image;
}
if (lastClicked != position) {
mThumbs[position] = R.drawable.image_required_when_grid_selected;
}
lastClicked = position;
mAdapter.notifyDataSetChanged(); // mAdapter is a reference to the GridView's adapter
}
lastClicked
将是您班级中存储最后点击位置的字段:
int lastClicked = -1; // -1 meaning there were no selection