try this:
private int prevPosition=-1;
and your onItemClick
use:
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long arg3) {
for (int i = 0; i < adapter.getChildCount(); i++) {
if (i == position) {
if(position!=prevPosition){
//set your selected color
adapter.getChildAt(i).setBackgroundColor(Color.BLUE);
prevPosition=position;
}else{
adapter.getChildAt(i).setBackgroundColor(Color.BLACK);
prevPosition=-1;
}
}else{
//set your normal color
adapter.getChildAt(i).setBackgroundColor(Color.BLACK);
}
}
}
});
Option 2
you can use drawable selector for your listview
in res/drawable
folder
background.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/pressed" />
<item android:state_focused="false"
android:drawable="@drawable/normal" />
</selector>
pressed.xml:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#000000"/> // set your selected color
<padding android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
</shape>
normal.xml:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<padding android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
</shape>
Now use it in your listview
in xml:
android:listSelector="@drawable/background"