Reputation: 1044
I'm trying to create a memory game - where I have 5x5 images on the screen and the user has to match the images. I've been using a GridView and populate it with images using a ImageAdapter. The game works something like this: - when a user matches 2 images - the images remain on the screen - when a user fails to match the 2 pictures - the imagess changes back to the question-mark. The problem is that I can't manage to keep the pictures previously matched on the screen - when I use the notifyDataSetChanged() method - all the screen is filled again with question marks. Here's my code:
// getView method in ImageAdapter
public View getView(int position, View convertView, ViewGroup arg2) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(4, 4, 4, 4);
} else {
imageView = (ImageView) convertView;
}
for(int i=0;i<16;i++)
{
if(mThumbIds[i].equals(R.drawable.ic_launcher))
{
imageView.setImageResource(R.drawable.ic_launcher);
}
else
imageView.setImageResource(R.drawable.q_mark);
}
return imageView;
}
// the onClickListener when a user selects 1 image
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
i++;
Toast.makeText(easyGame.this, "" + position, Toast.LENGTH_SHORT).show();
ImageView imgV=(ImageView)v;
if(i%2!=0)
{
firstClick=position;
imgV.setImageResource(ImageAdapter.mThumbIds[firstClick]);
}
else
{
secondClick=position;
imgV.setImageResource(ImageAdapter.mThumbIds[secondClick]);
}
if(i%2==0)
{
if(!(ImageAdapter.mThumbIds[firstClick].equals(ImageAdapter.mThumbIds[secondClick])))
{
Toast.makeText(easyGame.this, "Great!", Toast.LENGTH_SHORT).show();
ImageAdapter.mThumbIds[firstClick]=ImageAdapter.mThumbsIdsDone[0];
ImageAdapter.mThumbIds[secondClick]=ImageAdapter.mThumbsIdsDone[0];
im.notifyDataSetChanged();
gridview.setAdapter(im);
gridview.invalidate();
}
}
}
});
Can anyone help? Thanks!
Upvotes: 0
Views: 2000
Reputation: 711
// declare as class variable to keep track of views which should stay visible
private HashSet<Integer> keepVisibleViews = new HashSet<Integer>(25);
//in you on click listener
if(!(ImageAdapter.mThumbIds[firstClick].equals(ImageAdapter.mThumbIds[secondClick])))
{
// ... the rest of your code here
// keep track of views that should stay visible
keepVisibleViews.add(firstClick);
keepVisibleViews.add(secondClick);
}
// in your getView
// show ? mark if we should, else the picture
if (keepVisibleViews.contains(position)
setImageResource(ImageAdapter.mThumbIds[secondClick]);
else
imageView.setImageResource(R.drawable.q_mark);
Upvotes: 2