问题
I was trying to give background colour to selected items on GridView and I did it successfully using the following code-
gv.setOnItemClickListener(new OnItemClickListener() { // gv is object of GridView
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
gv.getChildAt(arg2).setBackgroundColor(Color.rgb(125, 125, 125));
}
});
Now I want to remove the given background colour when clicked on each item the next time. How can I do it ? Also, when clicked again the background colour should appear and on next click background colour should be removed.
回答1:
You can check the current color background and then perform some conditional operation to update the view accordingly.
gv.setOnItemClickListener(new OnItemClickListener() { // gv is object of GridView
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
View view = gv.getChildAt(arg2);
int desiredBackgroundColor = android.graphics.Color.rgb(125, 125, 125);
ColorDrawable viewColor = (ColorDrawable) view.getBackground();
if(viewColor == null) {
view.setBackgroundColor(desiredBackgroundColor);
return;
}
int currentColorId = viewColor.getColor();
if(currentColorId == desiredBackgroundColor) {
view.setBackgroundColor(Color.TRANSPARENT);
} else {
view.setBackgroundColor(desiredBackgroundColor);
}
}
});
来源:https://stackoverflow.com/questions/25834273/how-to-unselect-an-item-in-gridview-on-second-click-in-android