Wednesday, October 16, 2013

Android: Highlighting the selected item in the ExpandableListView



Steps to Highlight the selected item in the ExpandableListView

1.    In our ExpandableListView add android:choiceMode and android:listSelector attributes.
To use setItemChecked  we need to Set the checked state of the specified position. The is only valid if the choice mode has been set to CHOICE_MODE_SINGLE or CHOICE_MODE_MULTIPLE.
listSelector is used to indicate the currently selected item in the list. 

2.    Get the position of child using getPackedPositionForChild

3.    Get flat list position using getFlatListPosition.

4.    setItemChecked with the list position we get in step 2.

5.    Create row_highlighter.xml file.
xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@android:color/holo_orange_dark" android:state_activated="true"/>
<item android:drawable="@android:color/transparent"/>

</selector>

6.    Add android:background="@drawable/row_highlighter" attribute to child.xml of expandableListView.

7.    Source Code:
expandableListView.setOnChildClickListener(new OnChildClickListener() {

public boolean onChildClick(ExpandableListView parent, View v,
                                                int groupPosition, int childPosition, long id) {

int index = parent.getFlatListPosition(ExpandableListView
                   .getPackedPositionForChild(groupPosition, childPosition));
parent.setItemChecked(index, true);
                                     
return false;
}
});

output:


Improvements :-bd

If you want to see an example of customizing navigation drawer and highlighting of expanadablelistview then, see Custom Navigation Drawer  post. This example supports from API levels.

If you have any other quick hints that you think people will find useful, feel free to leave a comment.

4 comments :

  1. Thanks for the tutorial brother. but there is a problem:

    After collapse and expand again it does not work .. the highlight moved to another record

    ReplyDelete
    Replies
    1. When you collapse the group, the highlight won't be available. You should click the child record to get again the highlight colour.

      But I am surprised with the
      "After collapse and expand again it does not work .. the highlight moved to another record " comment.

      If possible share the code.

      Delete
    2. Yes it happened with me too. The highlight moves to another record on expanding or collapsing a group. This happens only for devices with API level below 11.

      Delete
  2. Thanks a lot!
    This works with 'CHOICE_MODE_MULTIPLE_MODAL'.
    Futuer, you can use ' android:background="?android:attr/activatedBackgroundIndicator" ' in the list item layout.
    This gives android themed selection indicator.

    ReplyDelete