private void setListviewSelection(final ListView list, final int pos) {
list.post(new Runnable() {
@Override
public void run() {
list.setSelection(pos);
for (int i = 0; i < list.getChildCount(); i++) {
View v = list.getChildAt(i);
if (i == pos && v != null)
v.setBackgroundColor(Color.argb(200, 51, 181, 229));
else if (v != null)
v.setBackgroundColor(Color.BLACK);
}
}
});
}
Here is a code I'm using to imitate a selection in my music player. The idea is that when user press Next or Previous button an element is highlighted in the ListView
, but this is not working the way I want, because setSelection
doesn't scroll smoothly and basically some elements are not highlighted correctly. For better explanation, what I'm actually trying to implement is a Winamp app which has that way of scrolling when you press next/previous button (when viewing your playlist).
Using setSelectionFromTop()
, smoothScrollToPosition()
didn't work correctly either.
http://bestsiteinthemultiverse.com/2009/12/android-selected-state-listview-example/
Here is the solution which works perfectly.