Search code examples
androidlistviewglow

Make a ListView item glow from code


Here's my problem : I have an Activity that includes a ListView with different locations listed, and a MapView with markers to these locations.

What I want right now is, when one of the MapView markers is clicked, to have the respective ListView item to be selected and to glow (as if it was clicked).

I found the methods ListView.setSelection(int) and ListView.requestChildFocus(View, View). The first one does almost what I want (if I have a long list, it goes through it until the item is visible) but it lacks a glow effect to explicitly show the item. About the second, I'm not sure what the second parameter is for (it's the previously focused view in the activity ?).

So, is there a way to have the item glow ? Like when you select it using a physical keyboard.

Thanks.

EDIT : subsidiary question, is it possible to get the standard drawable used as background when a ListView item is clicked ? Can it be found in R.attr like listPreferredItemHeight or something ?


Solution

  • Instead of making the items selected, you want to make them checked. This allows you to use a StateListDrawable to change the appearance of the item, since items don't stay selected when they are in touch mode. You have to put your ListView into single choice mode, make your listview item checkable, and use the StateListDrawable to change the appearance for checked items.

    To put your ListView in single choice mode:

    getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    

    Then when you want to highlight an item in your ListView, you do this:

    getListView().setItemChecked(index, true);
    

    I believe the root item of your row's layout must implement Checkable, you should be able to find example of CheckableRelativeLayout or CheckableLinearLayout online.

    That makes your item "checked" but you still need to make it glow, so in your row's layout you must use a StateListDrawable to change its appearance when it is checked by adding this to the layout:

    android:background="@color/list_view_item_selector"
    

    and creating a color\list_view_item_selector.xml file like this:

    <?xml version="1.0" encoding="UTF-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_checked="true" android:drawable="@color/selected_item" />
        <item android:drawable="@android:color/transparent" />
    </selector>