But when the listview loses focus, the text color of the last item is stay on selected state.
Please, remove the state_selected from your selector drawable xml and declare some choiceMode for it.
My ListView declaration:
<ListView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:choiceMode="singleChoice"
android:listSelector="@drawable/main_list_selector"
...
My selector for the list view (main_list_selector.xml):
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:drawable="@drawable/button_focused"/>
<item android:state_pressed="true" android:drawable="@drawable/button_checked_background"/>
<item android:state_activated="true" android:drawable="@drawable/button_checked_background"/>
</selector>
And row item layout:
<?xml version="1.0" encoding="utf-8"?>
<com.example.yourapp.ui.checkable.CheckableLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckedTextView
android:id="@+id/item_text_view"
...
android:background="@drawable/row_item background"/>
</com.example.yourapp.ui.checkable.CheckableLinearLayout>
row_item background:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/button_checked_background"/>
<item android:drawable="@android:color/transparent"/>
</selector>
As you see, I'm using CheckedTextView with background "row_item background" that has drawable state_checked, plus custon LinearLayout.
LinearLayout code:
public class CheckableLinearLayout extends LinearLayout implements Checkable {
private boolean checked = false;
public CheckableLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CheckableLinearLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean isChecked() {
return this.checked;
}
@Override
public void setChecked(boolean checked) {
this.checked = checked;
this.setSelected(this.checked);
final int childsCount = getChildCount();
for (int i = 0; i < childsCount; ++i) {
View child = getChildAt(i);
if (child instanceof Checkable) {
((Checkable) child).setChecked(checked);
}
}
}
@Override
public void toggle() {
setChecked(!this.checked);
}
}
Some of this hidden android logic I've found in this https://stackoverflow.com/a/7425650/2133585 answer.