I have a custom GridView with an ImageView and TextView in it. I want to colour a particular row when long press on it and to remove the background colour when long press the next time. Previously I asked a question of this type- How to unselect an item in gridview on second click in android?, so I referred it. But I can't apply that solution in this case-
gv.setOnItemLongClickListener(new OnItemLongClickListener() {
@SuppressLint("NewApi")
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(getBaseContext(), "Long Pressed",
Toast.LENGTH_LONG).show();
arg1.setBackgroundColor(Color.rgb(128, 128, 128));
longPressed();
return true;
}
});
How this code should be edited to give background colour and transparent colour on alternative long clicks ?
I would do the following:
1.- Add a var to keep track which background colour is going to be set next. For example a boolean could do the job:
boolean backgroundColorTransparent = false;
Then use it in your code to trigger the corresponding code and make sure you update the var for next long press click.
gv.setOnItemLongClickListener(new OnItemLongClickListener() {
@SuppressLint("NewApi")
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(getBaseContext(), "Long Pressed",
Toast.LENGTH_LONG).show();
if(backgroundColorTransparent){
arg1.setBackgroundColor(Color.TRANSPARENT);
longPressed();
backgroundColorTransparent = false;
}else{
arg1.setBackgroundColor(Color.rgb(128, 128, 128));
longPressed();
backgroundColorTransparent = true;
}
return true;
});