I have a listview which displays several items. Now I want to scroll to some specific item (e.g. the 33th item). I know that this can be done via
myList.setSelection(32);
But on the UI the item doesn't receive any highlighting (because it is in touch mode?!). How can I apply a specific background color for this item? I tried
myList.getSelection().getSelectedView().setBackgroundColor(Color.Red);
but i get a NullPointerException because getSelectedView() returns null. Is there a way to achieve this highlighting? I have to notify the user somehow about which item is the "active" one...
runOnUiThread(new Runnable() {
public void run() {
myList.requestFocus();
myList.setSelection(position);
}
});
2.To apply a specific color to an item. You can use customized listItem.
a. Set customized lisItem for your listView:
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, R.layout.customizedlistitem,arrListView);
myList.setAdapter(listAdapter);
b. In your layout folder, create customizedlistitem.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/customizedlistitem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/customizedbackground"/>
c. In your drawable folder, create customizedbackground.xml like this:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:state_pressed="false" android:drawable="@color/RED"></item>
<item android:state_pressed="true" android:drawable="@color/GREEN"></item>
<item android:drawable="@color/BLACK"></item> <!-- for other state -->
</selector>
d. Make sure color RED, GREEN and BLACK was defined in your project (you can define it in color.xml under values folder):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="RED">#FF0000</color>
<color name="GREEN">#008000</color>
<color name="BLACK">#000000</color>
</resources>
Try this, it will work-
myList.getChildAt(myList.getSelectedItemPosition()).setBackgroundColor(Color.RED);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With