I have a ListView & listselector.xml. Initially I set the item using setSeletion(position). But with this code the item doesn't get highlighted. It gets highlighted only when I click on an item.
ArrayAdapter<String> ad = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
timeListView = (ListView) findViewById(R.id.listList);
timeListView.setAdapter(ad);
timeListView.setOnItemClickListener(this);
timeListView.setSelector(R.drawable.listselector);
timeListView.setSelection(toSelectPos);
=============================
XML
<ListView android:id="@+id/listList" android:layout_width="match_parent" android:layout_height="wrap_content" android:dividerHeight="1dp" >
listselector.xml code
<?xml version="1.0" encoding="UTF-8"?>
<!-- listselector.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Selected -->
<item android:state_focused="true" android:state_selected="false"
android:drawable="@drawable/focused"/>
<!-- Pressed -->
<item android:state_selected="true" android:state_focused="false"
android:drawable="@drawable/selected" />
</selector>
The above code highlights full listview, I only want to highlight(change bg color) of the item. For that I believe I will have to create another xml for the item and set selector properties for the item & not list as done above. Correct me if am wrong.
The point is, in anyway only the selected item on click and on setSelection should be changed. With the above code, it doesn't change on setSelection, how to make that happen.
I looked in other Qs, but couldn't find the point I am looking for, so pls don't mark it as a duplicate for other Qs.
Thanks
As you probably already have seen in some answers here on stack-overflow, you can not put a View selected because it is implemented so that the User Interface has to be always in touch mode as you can see here However, there are some workarounds That you can do.
You can set your ListView onItemClick with the following listener:
OnItemClickListener itemClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int pos, long id) {
if (v == lastSelectedView) {
v.setBackgroundResource(0);
lastSelectedView = null;
} else if (v != lastSelectedView) {
if (lastSelectedView != null)
lastSelectedView
.setBackgroundColor(android.R.color.transparent);
lastSelectedView = v;
v.setBackgroundDrawable(v.getContext().getResources()
.getDrawable(R.drawable.some_row_background));
}
}
};
In this, you will color the listview
item as you want. However, there is a catch. The recycling of views will mark another view if you scroll down or up. You can "deselect" the view on a scroll or find a way to tag the view.
Best regards