I have a question that I have a custom grid view in which two images one is the background image and second is the check mark image, when I clicked on one Item of grid view
In your code you forgot to unselect all images except the current selected image. only you have done is setting background for selected image. you need to set unseleted images for others aswell
*Step-1*initialize selected position as -1 in GridAdapter class
int checked=0;
int selectedPosition = -1;
*Step-2*rewrite your onclick method as given below
@Override
public void onClick(View v) {
Log.i("Clicked", "Tag###########");
//img_select.setVisibility(View.INVISIBLE);
img_select.setFocusable(true);
img_select.setEnabled(true);
if(checked==0)
{
selectedPosition = position;
}
for(int i = 0; i<items.size(); i++){
if(i == selectedPosition){
img_select.setBackgroundResource(R.drawable.selectimage);
GreetingTextContainer greet = GreetingTextContainer.getSingletonObject();
greet.setPosition(position);
checked =1;
}else{
img_select.setBackgroundResource(0);
checked=0;
}
}
}
Well, there is one simple way to do this. You can keep reference of previously selected item. e.g. you make a variable at class level, where you are using the adapter. Then in your onClick listener, you un-select that image and set that variable with the current view(current image). e.g.
ImageView iv_selected = null;
// ..........
@Override
public void onClick(View view)
{
Log.i("Clicked", "Tag###########");
if(iv_selected != null)
{
// unselect the image here
}
// set this variable again e.g.
iv_selected = (ImageView)view;
//img_select.setVisibility(View.INVISIBLE);
img_select.setFocusable(true);
img_select.setEnabled(true);
if(checked==0)
{
img_select.setBackgroundResource(R.drawable.selectimage);
GreetingTextContainer greet = GreetingTextContainer.getSingletonObject();
greet.setPosition(position);
checked =1;
}
else
{
img_select.setBackgroundResource(0);
checked=0;
}
}
in this you'll always have the refernce of the single selected ImageView. So, you can uncheck it when you select something else. I hope you got the idea.
Do the following in your overrided method onItemClick
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> p, View view, int position,
long id) {
pos=position;
for(int i=0;i<ur_imageList.size();i++){
if(i==position){
//do nothing
}
else{
ur_imageList.get(i).isSelected=false;
}
}
if(ur_imageList.get(position).isSelected){//To deselect If selected
ur_imageList.get(position).isSelected=false;
}
else{
ur_imageList.get(position).isSelected=true;
}
gridview.invalidateViews();
}
});