How can I detect when the listview item has been clicked a second time?
I have made it so that when an item in the listview is clicked, the color is set to green. Now what I want is the color to change back on a second click.
Can anyone explain how I can do so?
Heres where I set the color green:
listView.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
parent.getChildAt(position).setBackgroundColor(Color.GREEN);
}
});
Just add an attribute variable in your Listener. Like this:
listView.setOnItemClickListener(new OnItemClickListener(){
private Set<Integer> hasClickedSet = new HashSet<Integer>();
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
if (hasClickedSet.contains(position)){
v.setBackgroundColor(Color.BLACK);
} else {
v.setBackgroundColor(Color.GREEN);
hasClickedSet.add(position);
}
}
and you need not calling parent.getChildAt(position). Just use the 'v' parameter.
========EDIT============ ok, try this:
listView.setOnItemClickListener(new OnItemClickListener(){
private SparseArray<Boolean> hasClicked = new SparseArray<Boolean>();
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
if (hasClicked.get(position, false)){
v.setBackgroundColor(Color.RED);
hasClicked.put(position, false);
} else {
v.setBackgroundColor(Color.GREEN);
hasClicked.put(position, true);
}
}