Android ListView selected item stay highlighted
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
for (int j = 0; j < adapterView.getChildCount(); j++)
adapterView.getChildAt(j).setBackgroundColor(Color.TRANSPARENT);
// change the background color of the selected element
view.setBackgroundColor(Color.LTGRAY);
});
Perhaps you might want to save the current selected element in a global variable using the index i.
I found the proper way. It's very simple. In resource describe following:
android:choiceMode="singleChoice"
android:listSelector="#666666"
(or you may specify a resource link instead of color value)
Programmatical:
listView.setSelector(Drawable selector);
listView.setSelector(int resourceId);
listView.setChoiceMode(int mode);
mode can be one of these: AbsListView.CHOICE_MODE_SINGLE, AbsListView.CHOICE_MODE_MULTIPLE, AbsListView.CHOICE_MODE_NONE (default)
(AbsListView is the abstract ancestor for the ListView class)
P.S. manipulations with onItemClick and changing view background are bankrupt, because a view itself is a temporary object. Hence you must not to track a view.
If our list is long enough, the views associated with scrolled out items will be removed from hierarchy, and will be recreated when those items will shown again (with cached display options, such as background). So, the view we have tracked is now not an actual view of the item, and changing its background does nothing to the actual item view. As a result we have multiple items selected.
To hold the color of listview item when you press it, include the following line in your listview item layout:
android:background="@drawable/bg_key"
Then define bg_key.xml
in drawable
folder like this:
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:drawable="@color/pressed_color"/>
<item
android:drawable="@color/default_color" />
</selector>
Finally, include this in your ListView
onClickListener
:
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {
view.setSelected(true);
... // Anything
}
});
This way, only one item will be color-selected at any time. You can define your color values in res/values/colors.xml
with something like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="pressed_color">#4d90fe</color>
<color name="default_color">#ffffff</color>
</resources>