ExpandableListView.java revision 47ccdf3760635a695b7c417a0df02f7e86ce6262
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.widget;
18
19import com.android.internal.R;
20
21import android.content.Context;
22import android.content.res.TypedArray;
23import android.graphics.Canvas;
24import android.graphics.Rect;
25import android.graphics.drawable.ColorDrawable;
26import android.graphics.drawable.Drawable;
27import android.os.Parcel;
28import android.os.Parcelable;
29import android.util.AttributeSet;
30import android.view.ContextMenu;
31import android.view.SoundEffectConstants;
32import android.view.View;
33import android.view.ContextMenu.ContextMenuInfo;
34import android.widget.ExpandableListConnector.PositionMetadata;
35
36import java.util.ArrayList;
37
38/**
39 * A view that shows items in a vertically scrolling two-level list. This
40 * differs from the {@link ListView} by allowing two levels: groups which can
41 * individually be expanded to show its children. The items come from the
42 * {@link ExpandableListAdapter} associated with this view.
43 * <p>
44 * Expandable lists are able to show an indicator beside each item to display
45 * the item's current state (the states are usually one of expanded group,
46 * collapsed group, child, or last child). Use
47 * {@link #setChildIndicator(Drawable)} or {@link #setGroupIndicator(Drawable)}
48 * (or the corresponding XML attributes) to set these indicators (see the docs
49 * for each method to see additional state that each Drawable can have). The
50 * default style for an {@link ExpandableListView} provides indicators which
51 * will be shown next to Views given to the {@link ExpandableListView}. The
52 * layouts android.R.layout.simple_expandable_list_item_1 and
53 * android.R.layout.simple_expandable_list_item_2 (which should be used with
54 * {@link SimpleCursorTreeAdapter}) contain the preferred position information
55 * for indicators.
56 * <p>
57 * The context menu information set by an {@link ExpandableListView} will be a
58 * {@link ExpandableListContextMenuInfo} object with
59 * {@link ExpandableListContextMenuInfo#packedPosition} being a packed position
60 * that can be used with {@link #getPackedPositionType(long)} and the other
61 * similar methods.
62 * <p>
63 * <em><b>Note:</b></em> You cannot use the value <code>wrap_content</code>
64 * for the <code>android:layout_height</code> attribute of a
65 * ExpandableListView in XML if the parent's size is also not strictly specified
66 * (for example, if the parent were ScrollView you could not specify
67 * wrap_content since it also can be any length. However, you can use
68 * wrap_content if the ExpandableListView parent has a specific size, such as
69 * 100 pixels.
70 *
71 * @attr ref android.R.styleable#ExpandableListView_groupIndicator
72 * @attr ref android.R.styleable#ExpandableListView_indicatorLeft
73 * @attr ref android.R.styleable#ExpandableListView_indicatorRight
74 * @attr ref android.R.styleable#ExpandableListView_childIndicator
75 * @attr ref android.R.styleable#ExpandableListView_childIndicatorLeft
76 * @attr ref android.R.styleable#ExpandableListView_childIndicatorRight
77 * @attr ref android.R.styleable#ExpandableListView_childDivider
78 */
79public class ExpandableListView extends ListView {
80
81    /**
82     * The packed position represents a group.
83     */
84    public static final int PACKED_POSITION_TYPE_GROUP = 0;
85
86    /**
87     * The packed position represents a child.
88     */
89    public static final int PACKED_POSITION_TYPE_CHILD = 1;
90
91    /**
92     * The packed position represents a neither/null/no preference.
93     */
94    public static final int PACKED_POSITION_TYPE_NULL = 2;
95
96    /**
97     * The value for a packed position that represents neither/null/no
98     * preference. This value is not otherwise possible since a group type
99     * (first bit 0) should not have a child position filled.
100     */
101    public static final long PACKED_POSITION_VALUE_NULL = 0x00000000FFFFFFFFL;
102
103    /** The mask (in packed position representation) for the child */
104    private static final long PACKED_POSITION_MASK_CHILD = 0x00000000FFFFFFFFL;
105
106    /** The mask (in packed position representation) for the group */
107    private static final long PACKED_POSITION_MASK_GROUP = 0x7FFFFFFF00000000L;
108
109    /** The mask (in packed position representation) for the type */
110    private static final long PACKED_POSITION_MASK_TYPE  = 0x8000000000000000L;
111
112    /** The shift amount (in packed position representation) for the group */
113    private static final long PACKED_POSITION_SHIFT_GROUP = 32;
114
115    /** The shift amount (in packed position representation) for the type */
116    private static final long PACKED_POSITION_SHIFT_TYPE  = 63;
117
118    /** The mask (in integer child position representation) for the child */
119    private static final long PACKED_POSITION_INT_MASK_CHILD = 0xFFFFFFFF;
120
121    /** The mask (in integer group position representation) for the group */
122    private static final long PACKED_POSITION_INT_MASK_GROUP = 0x7FFFFFFF;
123
124    /** Serves as the glue/translator between a ListView and an ExpandableListView */
125    private ExpandableListConnector mConnector;
126
127    /** Gives us Views through group+child positions */
128    private ExpandableListAdapter mAdapter;
129
130    /** Left bound for drawing the indicator. */
131    private int mIndicatorLeft;
132
133    /** Right bound for drawing the indicator. */
134    private int mIndicatorRight;
135
136    /**
137     * Left bound for drawing the indicator of a child. Value of
138     * {@link #CHILD_INDICATOR_INHERIT} means use mIndicatorLeft.
139     */
140    private int mChildIndicatorLeft;
141
142    /**
143     * Right bound for drawing the indicator of a child. Value of
144     * {@link #CHILD_INDICATOR_INHERIT} means use mIndicatorRight.
145     */
146    private int mChildIndicatorRight;
147
148    /**
149     * Denotes when a child indicator should inherit this bound from the generic
150     * indicator bounds
151     */
152    public static final int CHILD_INDICATOR_INHERIT = -1;
153
154    /** The indicator drawn next to a group. */
155    private Drawable mGroupIndicator;
156
157    /** The indicator drawn next to a child. */
158    private Drawable mChildIndicator;
159
160    private static final int[] EMPTY_STATE_SET = {};
161
162    /** State indicating the group is expanded. */
163    private static final int[] GROUP_EXPANDED_STATE_SET =
164            {R.attr.state_expanded};
165
166    /** State indicating the group is empty (has no children). */
167    private static final int[] GROUP_EMPTY_STATE_SET =
168            {R.attr.state_empty};
169
170    /** State indicating the group is expanded and empty (has no children). */
171    private static final int[] GROUP_EXPANDED_EMPTY_STATE_SET =
172            {R.attr.state_expanded, R.attr.state_empty};
173
174    /** States for the group where the 0th bit is expanded and 1st bit is empty. */
175    private static final int[][] GROUP_STATE_SETS = {
176         EMPTY_STATE_SET, // 00
177         GROUP_EXPANDED_STATE_SET, // 01
178         GROUP_EMPTY_STATE_SET, // 10
179         GROUP_EXPANDED_EMPTY_STATE_SET // 11
180    };
181
182    /** State indicating the child is the last within its group. */
183    private static final int[] CHILD_LAST_STATE_SET =
184            {R.attr.state_last};
185
186    /** Drawable to be used as a divider when it is adjacent to any children */
187    private Drawable mChildDivider;
188    private boolean mClipChildDivider;
189
190    // Bounds of the indicator to be drawn
191    private final Rect mIndicatorRect = new Rect();
192
193    public ExpandableListView(Context context) {
194        this(context, null);
195    }
196
197    public ExpandableListView(Context context, AttributeSet attrs) {
198        this(context, attrs, com.android.internal.R.attr.expandableListViewStyle);
199    }
200
201    public ExpandableListView(Context context, AttributeSet attrs, int defStyle) {
202        super(context, attrs, defStyle);
203
204        TypedArray a =
205            context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.ExpandableListView, defStyle,
206                    0);
207
208        mGroupIndicator = a
209                .getDrawable(com.android.internal.R.styleable.ExpandableListView_groupIndicator);
210        mChildIndicator = a
211                .getDrawable(com.android.internal.R.styleable.ExpandableListView_childIndicator);
212        mIndicatorLeft = a
213                .getDimensionPixelSize(com.android.internal.R.styleable.ExpandableListView_indicatorLeft, 0);
214        mIndicatorRight = a
215                .getDimensionPixelSize(com.android.internal.R.styleable.ExpandableListView_indicatorRight, 0);
216        mChildIndicatorLeft = a.getDimensionPixelSize(
217                com.android.internal.R.styleable.ExpandableListView_childIndicatorLeft, CHILD_INDICATOR_INHERIT);
218        mChildIndicatorRight = a.getDimensionPixelSize(
219                com.android.internal.R.styleable.ExpandableListView_childIndicatorRight, CHILD_INDICATOR_INHERIT);
220        mChildDivider = a.getDrawable(com.android.internal.R.styleable.ExpandableListView_childDivider);
221
222        a.recycle();
223    }
224
225
226    @Override
227    protected void dispatchDraw(Canvas canvas) {
228        // Draw children, etc.
229        super.dispatchDraw(canvas);
230
231        // If we have any indicators to draw, we do it here
232        if ((mChildIndicator == null) && (mGroupIndicator == null)) {
233            return;
234        }
235
236        int saveCount = 0;
237        final boolean clipToPadding = (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
238        if (clipToPadding) {
239            saveCount = canvas.save();
240            final int scrollX = mScrollX;
241            final int scrollY = mScrollY;
242            canvas.clipRect(scrollX + mPaddingLeft, scrollY + mPaddingTop,
243                    scrollX + mRight - mLeft - mPaddingRight,
244                    scrollY + mBottom - mTop - mPaddingBottom);
245        }
246
247        final int headerViewsCount = getHeaderViewsCount();
248
249        final int lastChildFlPos = mItemCount - getFooterViewsCount() - headerViewsCount - 1;
250
251        final int myB = mBottom;
252
253        PositionMetadata pos;
254        View item;
255        Drawable indicator;
256        int t, b;
257
258        // Start at a value that is neither child nor group
259        int lastItemType = ~(ExpandableListPosition.CHILD | ExpandableListPosition.GROUP);
260
261        final Rect indicatorRect = mIndicatorRect;
262
263        // The "child" mentioned in the following two lines is this
264        // View's child, not referring to an expandable list's
265        // notion of a child (as opposed to a group)
266        final int childCount = getChildCount();
267        for (int i = 0, childFlPos = mFirstPosition - headerViewsCount; i < childCount;
268             i++, childFlPos++) {
269
270            if (childFlPos < 0) {
271                // This child is header
272                continue;
273            } else if (childFlPos > lastChildFlPos) {
274                // This child is footer, so are all subsequent children
275                break;
276            }
277
278            item = getChildAt(i);
279            t = item.getTop();
280            b = item.getBottom();
281
282            // This item isn't on the screen
283            if ((b < 0) || (t > myB)) continue;
284
285            // Get more expandable list-related info for this item
286            pos = mConnector.getUnflattenedPos(childFlPos);
287
288            // If this item type and the previous item type are different, then we need to change
289            // the left & right bounds
290            if (pos.position.type != lastItemType) {
291                if (pos.position.type == ExpandableListPosition.CHILD) {
292                    indicatorRect.left = (mChildIndicatorLeft == CHILD_INDICATOR_INHERIT) ?
293                            mIndicatorLeft : mChildIndicatorLeft;
294                    indicatorRect.right = (mChildIndicatorRight == CHILD_INDICATOR_INHERIT) ?
295                            mIndicatorRight : mChildIndicatorRight;
296                } else {
297                    indicatorRect.left = mIndicatorLeft;
298                    indicatorRect.right = mIndicatorRight;
299                }
300
301                lastItemType = pos.position.type;
302            }
303
304            if (indicatorRect.left != indicatorRect.right) {
305                // Use item's full height + the divider height
306                if (mStackFromBottom) {
307                    // See ListView#dispatchDraw
308                    indicatorRect.top = t;// - mDividerHeight;
309                    indicatorRect.bottom = b;
310                } else {
311                    indicatorRect.top = t;
312                    indicatorRect.bottom = b;// + mDividerHeight;
313                }
314
315                // Get the indicator (with its state set to the item's state)
316                indicator = getIndicator(pos);
317                if (indicator != null) {
318                    // Draw the indicator
319                    indicator.setBounds(indicatorRect);
320                    indicator.draw(canvas);
321                }
322            }
323
324            pos.recycle();
325        }
326
327        if (clipToPadding) {
328            canvas.restoreToCount(saveCount);
329        }
330    }
331
332    /**
333     * Gets the indicator for the item at the given position. If the indicator
334     * is stateful, the state will be given to the indicator.
335     *
336     * @param pos The flat list position of the item whose indicator
337     *            should be returned.
338     * @return The indicator in the proper state.
339     */
340    private Drawable getIndicator(PositionMetadata pos) {
341        Drawable indicator;
342
343        if (pos.position.type == ExpandableListPosition.GROUP) {
344            indicator = mGroupIndicator;
345
346            if (indicator != null && indicator.isStateful()) {
347                // Empty check based on availability of data.  If the groupMetadata isn't null,
348                // we do a check on it. Otherwise, the group is collapsed so we consider it
349                // empty for performance reasons.
350                boolean isEmpty = (pos.groupMetadata == null) ||
351                        (pos.groupMetadata.lastChildFlPos == pos.groupMetadata.flPos);
352
353                final int stateSetIndex =
354                    (pos.isExpanded() ? 1 : 0) | // Expanded?
355                    (isEmpty ? 2 : 0); // Empty?
356                indicator.setState(GROUP_STATE_SETS[stateSetIndex]);
357            }
358        } else {
359            indicator = mChildIndicator;
360
361            if (indicator != null && indicator.isStateful()) {
362                // No need for a state sets array for the child since it only has two states
363                final int stateSet[] = pos.position.flatListPos == pos.groupMetadata.lastChildFlPos
364                        ? CHILD_LAST_STATE_SET
365                        : EMPTY_STATE_SET;
366                indicator.setState(stateSet);
367            }
368        }
369
370        return indicator;
371    }
372
373    /**
374     * Sets the drawable that will be drawn adjacent to every child in the list. This will
375     * be drawn using the same height as the normal divider ({@link #setDivider(Drawable)}) or
376     * if it does not have an intrinsic height, the height set by {@link #setDividerHeight(int)}.
377     *
378     * @param childDivider The drawable to use.
379     */
380    public void setChildDivider(Drawable childDivider) {
381        mChildDivider = childDivider;
382        mClipChildDivider = childDivider != null && childDivider instanceof ColorDrawable;
383    }
384
385    @Override
386    void drawDivider(Canvas canvas, Rect bounds, int childIndex) {
387        int flatListPosition = childIndex + mFirstPosition;
388
389        // Only proceed as possible child if the divider isn't above all items (if it is above
390        // all items, then the item below it has to be a group)
391        if (flatListPosition >= 0) {
392            PositionMetadata pos = mConnector.getUnflattenedPos(flatListPosition);
393            // If this item is a child, or it is a non-empty group that is expanded
394            if ((pos.position.type == ExpandableListPosition.CHILD) || (pos.isExpanded() &&
395                    pos.groupMetadata.lastChildFlPos != pos.groupMetadata.flPos)) {
396                // These are the cases where we draw the child divider
397                final Drawable divider = mChildDivider;
398                final boolean clip = mClipChildDivider;
399                if (!clip) {
400                    divider.setBounds(bounds);
401                } else {
402                    canvas.save();
403                    canvas.clipRect(bounds);
404                }
405                divider.draw(canvas);
406                if (clip) {
407                    canvas.restore();
408                }
409                pos.recycle();
410                return;
411            }
412            pos.recycle();
413        }
414
415        // Otherwise draw the default divider
416        super.drawDivider(canvas, bounds, flatListPosition);
417    }
418
419    /**
420     * This overloaded method should not be used, instead use
421     * {@link #setAdapter(ExpandableListAdapter)}.
422     * <p>
423     * {@inheritDoc}
424     */
425    @Override
426    public void setAdapter(ListAdapter adapter) {
427        throw new RuntimeException(
428                "For ExpandableListView, use setAdapter(ExpandableListAdapter) instead of " +
429                "setAdapter(ListAdapter)");
430    }
431
432    /**
433     * This method should not be used, use {@link #getExpandableListAdapter()}.
434     */
435    @Override
436    public ListAdapter getAdapter() {
437        /*
438         * The developer should never really call this method on an
439         * ExpandableListView, so it would be nice to throw a RuntimeException,
440         * but AdapterView calls this
441         */
442        return super.getAdapter();
443    }
444
445    /**
446     * Register a callback to be invoked when an item has been clicked and the
447     * caller prefers to receive a ListView-style position instead of a group
448     * and/or child position. In most cases, the caller should use
449     * {@link #setOnGroupClickListener} and/or {@link #setOnChildClickListener}.
450     * <p />
451     * {@inheritDoc}
452     */
453    @Override
454    public void setOnItemClickListener(OnItemClickListener l) {
455        super.setOnItemClickListener(l);
456    }
457
458    /**
459     * Sets the adapter that provides data to this view.
460     * @param adapter The adapter that provides data to this view.
461     */
462    public void setAdapter(ExpandableListAdapter adapter) {
463        // Set member variable
464        mAdapter = adapter;
465
466        if (adapter != null) {
467            // Create the connector
468            mConnector = new ExpandableListConnector(adapter);
469        } else {
470            mConnector = null;
471        }
472
473        // Link the ListView (superclass) to the expandable list data through the connector
474        super.setAdapter(mConnector);
475    }
476
477    /**
478     * Gets the adapter that provides data to this view.
479     * @return The adapter that provides data to this view.
480     */
481    public ExpandableListAdapter getExpandableListAdapter() {
482        return mAdapter;
483    }
484
485    private boolean isHeaderOrFooterPosition(int position) {
486        final int footerViewsStart = mItemCount - getFooterViewsCount();
487        return (position < getHeaderViewsCount() || position >= footerViewsStart);
488    }
489
490    @Override
491    public boolean performItemClick(View v, int position, long id) {
492        // Ignore clicks in header/footers
493        if (isHeaderOrFooterPosition(position)) {
494            // Clicked on a header/footer, so ignore pass it on to super
495            return super.performItemClick(v, position, id);
496        }
497
498        // Internally handle the item click
499        final int headerViewsCount = getHeaderViewsCount();
500        return handleItemClick(v, position - headerViewsCount, id);
501    }
502
503    /**
504     * This will either expand/collapse groups (if a group was clicked) or pass
505     * on the click to the proper child (if a child was clicked)
506     *
507     * @param position The flat list position. This has already been factored to
508     *            remove the header/footer.
509     * @param id The ListAdapter ID, not the group or child ID.
510     */
511    boolean handleItemClick(View v, int position, long id) {
512        final PositionMetadata posMetadata = mConnector.getUnflattenedPos(position);
513
514        id = getChildOrGroupId(posMetadata.position);
515
516        boolean returnValue;
517        if (posMetadata.position.type == ExpandableListPosition.GROUP) {
518            /* It's a group, so handle collapsing/expanding */
519
520            /* It's a group click, so pass on event */
521            if (mOnGroupClickListener != null) {
522                if (mOnGroupClickListener.onGroupClick(this, v,
523                        posMetadata.position.groupPos, id)) {
524                    posMetadata.recycle();
525                    return true;
526                }
527            }
528
529            if (posMetadata.isExpanded()) {
530                /* Collapse it */
531                mConnector.collapseGroup(posMetadata);
532
533                playSoundEffect(SoundEffectConstants.CLICK);
534
535                if (mOnGroupCollapseListener != null) {
536                    mOnGroupCollapseListener.onGroupCollapse(posMetadata.position.groupPos);
537                }
538            } else {
539                /* Expand it */
540                mConnector.expandGroup(posMetadata);
541
542                playSoundEffect(SoundEffectConstants.CLICK);
543
544                if (mOnGroupExpandListener != null) {
545                    mOnGroupExpandListener.onGroupExpand(posMetadata.position.groupPos);
546                }
547
548                final int groupPos = posMetadata.position.groupPos;
549                final int groupFlatPos = posMetadata.position.flatListPos;
550
551                smoothScrollToPosition(groupFlatPos + mAdapter.getChildrenCount(groupPos),
552                        groupFlatPos);
553            }
554
555            returnValue = true;
556        } else {
557            /* It's a child, so pass on event */
558            if (mOnChildClickListener != null) {
559                playSoundEffect(SoundEffectConstants.CLICK);
560                return mOnChildClickListener.onChildClick(this, v, posMetadata.position.groupPos,
561                        posMetadata.position.childPos, id);
562            }
563
564            returnValue = false;
565        }
566
567        posMetadata.recycle();
568
569        return returnValue;
570    }
571
572    /**
573     * Expand a group in the grouped list view
574     *
575     * @param groupPos the group to be expanded
576     * @return True if the group was expanded, false otherwise (if the group
577     *         was already expanded, this will return false)
578     */
579    public boolean expandGroup(int groupPos) {
580        boolean retValue = mConnector.expandGroup(groupPos);
581
582        if (mOnGroupExpandListener != null) {
583            mOnGroupExpandListener.onGroupExpand(groupPos);
584        }
585
586        return retValue;
587    }
588
589    /**
590     * Collapse a group in the grouped list view
591     *
592     * @param groupPos position of the group to collapse
593     * @return True if the group was collapsed, false otherwise (if the group
594     *         was already collapsed, this will return false)
595     */
596    public boolean collapseGroup(int groupPos) {
597        boolean retValue = mConnector.collapseGroup(groupPos);
598
599        if (mOnGroupCollapseListener != null) {
600            mOnGroupCollapseListener.onGroupCollapse(groupPos);
601        }
602
603        return retValue;
604    }
605
606    /** Used for being notified when a group is collapsed */
607    public interface OnGroupCollapseListener {
608        /**
609         * Callback method to be invoked when a group in this expandable list has
610         * been collapsed.
611         *
612         * @param groupPosition The group position that was collapsed
613         */
614        void onGroupCollapse(int groupPosition);
615    }
616
617    private OnGroupCollapseListener mOnGroupCollapseListener;
618
619    public void setOnGroupCollapseListener(
620            OnGroupCollapseListener onGroupCollapseListener) {
621        mOnGroupCollapseListener = onGroupCollapseListener;
622    }
623
624    /** Used for being notified when a group is expanded */
625    public interface OnGroupExpandListener {
626        /**
627         * Callback method to be invoked when a group in this expandable list has
628         * been expanded.
629         *
630         * @param groupPosition The group position that was expanded
631         */
632        void onGroupExpand(int groupPosition);
633    }
634
635    private OnGroupExpandListener mOnGroupExpandListener;
636
637    public void setOnGroupExpandListener(
638            OnGroupExpandListener onGroupExpandListener) {
639        mOnGroupExpandListener = onGroupExpandListener;
640    }
641
642    /**
643     * Interface definition for a callback to be invoked when a group in this
644     * expandable list has been clicked.
645     */
646    public interface OnGroupClickListener {
647        /**
648         * Callback method to be invoked when a group in this expandable list has
649         * been clicked.
650         *
651         * @param parent The ExpandableListConnector where the click happened
652         * @param v The view within the expandable list/ListView that was clicked
653         * @param groupPosition The group position that was clicked
654         * @param id The row id of the group that was clicked
655         * @return True if the click was handled
656         */
657        boolean onGroupClick(ExpandableListView parent, View v, int groupPosition,
658                long id);
659    }
660
661    private OnGroupClickListener mOnGroupClickListener;
662
663    public void setOnGroupClickListener(OnGroupClickListener onGroupClickListener) {
664        mOnGroupClickListener = onGroupClickListener;
665    }
666
667    /**
668     * Interface definition for a callback to be invoked when a child in this
669     * expandable list has been clicked.
670     */
671    public interface OnChildClickListener {
672        /**
673         * Callback method to be invoked when a child in this expandable list has
674         * been clicked.
675         *
676         * @param parent The ExpandableListView where the click happened
677         * @param v The view within the expandable list/ListView that was clicked
678         * @param groupPosition The group position that contains the child that
679         *        was clicked
680         * @param childPosition The child position within the group
681         * @param id The row id of the child that was clicked
682         * @return True if the click was handled
683         */
684        boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
685                int childPosition, long id);
686    }
687
688    private OnChildClickListener mOnChildClickListener;
689
690    public void setOnChildClickListener(OnChildClickListener onChildClickListener) {
691        mOnChildClickListener = onChildClickListener;
692    }
693
694    /**
695     * Converts a flat list position (the raw position of an item (child or group)
696     * in the list) to an group and/or child position (represented in a
697     * packed position). This is useful in situations where the caller needs to
698     * use the underlying {@link ListView}'s methods. Use
699     * {@link ExpandableListView#getPackedPositionType} ,
700     * {@link ExpandableListView#getPackedPositionChild},
701     * {@link ExpandableListView#getPackedPositionGroup} to unpack.
702     *
703     * @param flatListPosition The flat list position to be converted.
704     * @return The group and/or child position for the given flat list position
705     *         in packed position representation. #PACKED_POSITION_VALUE_NULL if
706     *         the position corresponds to a header or a footer item.
707     */
708    public long getExpandableListPosition(int flatListPosition) {
709        if (isHeaderOrFooterPosition(flatListPosition)) {
710            return PACKED_POSITION_VALUE_NULL;
711        }
712
713        final int shiftedPosition = flatListPosition - getHeaderViewsCount();
714        PositionMetadata pm = mConnector.getUnflattenedPos(shiftedPosition);
715        long packedPos = pm.position.getPackedPosition();
716        pm.recycle();
717        return packedPos;
718    }
719
720    /**
721     * Converts a group and/or child position to a flat list position. This is
722     * useful in situations where the caller needs to use the underlying
723     * {@link ListView}'s methods.
724     *
725     * @param packedPosition The group and/or child positions to be converted in
726     *            packed position representation. Use
727     *            {@link #getPackedPositionForChild(int, int)} or
728     *            {@link #getPackedPositionForGroup(int)}.
729     * @return The flat list position for the given child or group.
730     */
731    public int getFlatListPosition(long packedPosition) {
732        PositionMetadata pm = mConnector.getFlattenedPos(ExpandableListPosition
733                .obtainPosition(packedPosition));
734        int retValue = pm.position.flatListPos;
735        pm.recycle();
736        return retValue + getHeaderViewsCount();
737    }
738
739    /**
740     * Gets the position of the currently selected group or child (along with
741     * its type). Can return {@link #PACKED_POSITION_VALUE_NULL} if no selection.
742     *
743     * @return A packed position containing the currently selected group or
744     *         child's position and type. #PACKED_POSITION_VALUE_NULL if no selection
745     *         or if selection is on a header or a footer item.
746     */
747    public long getSelectedPosition() {
748        final int selectedPos = getSelectedItemPosition();
749
750        // The case where there is no selection (selectedPos == -1) is also handled here.
751        return getExpandableListPosition(selectedPos);
752    }
753
754    /**
755     * Gets the ID of the currently selected group or child. Can return -1 if no
756     * selection.
757     *
758     * @return The ID of the currently selected group or child. -1 if no
759     *         selection.
760     */
761    public long getSelectedId() {
762        long packedPos = getSelectedPosition();
763        if (packedPos == PACKED_POSITION_VALUE_NULL) return -1;
764
765        int groupPos = getPackedPositionGroup(packedPos);
766
767        if (getPackedPositionType(packedPos) == PACKED_POSITION_TYPE_GROUP) {
768            // It's a group
769            return mAdapter.getGroupId(groupPos);
770        } else {
771            // It's a child
772            return mAdapter.getChildId(groupPos, getPackedPositionChild(packedPos));
773        }
774    }
775
776    /**
777     * Sets the selection to the specified group.
778     * @param groupPosition The position of the group that should be selected.
779     */
780    public void setSelectedGroup(int groupPosition) {
781        ExpandableListPosition elGroupPos = ExpandableListPosition
782                .obtainGroupPosition(groupPosition);
783        PositionMetadata pm = mConnector.getFlattenedPos(elGroupPos);
784        elGroupPos.recycle();
785        super.setSelection(pm.position.flatListPos);
786        pm.recycle();
787    }
788
789    /**
790     * Sets the selection to the specified child. If the child is in a collapsed
791     * group, the group will only be expanded and child subsequently selected if
792     * shouldExpandGroup is set to true, otherwise the method will return false.
793     *
794     * @param groupPosition The position of the group that contains the child.
795     * @param childPosition The position of the child within the group.
796     * @param shouldExpandGroup Whether the child's group should be expanded if
797     *            it is collapsed.
798     * @return Whether the selection was successfully set on the child.
799     */
800    public boolean setSelectedChild(int groupPosition, int childPosition, boolean shouldExpandGroup) {
801        ExpandableListPosition elChildPos = ExpandableListPosition.obtainChildPosition(
802                groupPosition, childPosition);
803        PositionMetadata flatChildPos = mConnector.getFlattenedPos(elChildPos);
804
805        if (flatChildPos == null) {
806            // The child's group isn't expanded
807
808            // Shouldn't expand the group, so return false for we didn't set the selection
809            if (!shouldExpandGroup) return false;
810
811            expandGroup(groupPosition);
812
813            flatChildPos = mConnector.getFlattenedPos(elChildPos);
814
815            // Sanity check
816            if (flatChildPos == null) {
817                throw new IllegalStateException("Could not find child");
818            }
819        }
820
821        super.setSelection(flatChildPos.position.flatListPos);
822
823        elChildPos.recycle();
824        flatChildPos.recycle();
825
826        return true;
827    }
828
829    /**
830     * Whether the given group is currently expanded.
831     *
832     * @param groupPosition The group to check.
833     * @return Whether the group is currently expanded.
834     */
835    public boolean isGroupExpanded(int groupPosition) {
836        return mConnector.isGroupExpanded(groupPosition);
837    }
838
839    /**
840     * Gets the type of a packed position. See
841     * {@link #getPackedPositionForChild(int, int)}.
842     *
843     * @param packedPosition The packed position for which to return the type.
844     * @return The type of the position contained within the packed position,
845     *         either {@link #PACKED_POSITION_TYPE_CHILD}, {@link #PACKED_POSITION_TYPE_GROUP}, or
846     *         {@link #PACKED_POSITION_TYPE_NULL}.
847     */
848    public static int getPackedPositionType(long packedPosition) {
849        if (packedPosition == PACKED_POSITION_VALUE_NULL) {
850            return PACKED_POSITION_TYPE_NULL;
851        }
852
853        return (packedPosition & PACKED_POSITION_MASK_TYPE) == PACKED_POSITION_MASK_TYPE
854                ? PACKED_POSITION_TYPE_CHILD
855                : PACKED_POSITION_TYPE_GROUP;
856    }
857
858    /**
859     * Gets the group position from a packed position. See
860     * {@link #getPackedPositionForChild(int, int)}.
861     *
862     * @param packedPosition The packed position from which the group position
863     *            will be returned.
864     * @return The group position portion of the packed position. If this does
865     *         not contain a group, returns -1.
866     */
867    public static int getPackedPositionGroup(long packedPosition) {
868        // Null
869        if (packedPosition == PACKED_POSITION_VALUE_NULL) return -1;
870
871        return (int) ((packedPosition & PACKED_POSITION_MASK_GROUP) >> PACKED_POSITION_SHIFT_GROUP);
872    }
873
874    /**
875     * Gets the child position from a packed position that is of
876     * {@link #PACKED_POSITION_TYPE_CHILD} type (use {@link #getPackedPositionType(long)}).
877     * To get the group that this child belongs to, use
878     * {@link #getPackedPositionGroup(long)}. See
879     * {@link #getPackedPositionForChild(int, int)}.
880     *
881     * @param packedPosition The packed position from which the child position
882     *            will be returned.
883     * @return The child position portion of the packed position. If this does
884     *         not contain a child, returns -1.
885     */
886    public static int getPackedPositionChild(long packedPosition) {
887        // Null
888        if (packedPosition == PACKED_POSITION_VALUE_NULL) return -1;
889
890        // Group since a group type clears this bit
891        if ((packedPosition & PACKED_POSITION_MASK_TYPE) != PACKED_POSITION_MASK_TYPE) return -1;
892
893        return (int) (packedPosition & PACKED_POSITION_MASK_CHILD);
894    }
895
896    /**
897     * Returns the packed position representation of a child's position.
898     * <p>
899     * In general, a packed position should be used in
900     * situations where the position given to/returned from an
901     * {@link ExpandableListAdapter} or {@link ExpandableListView} method can
902     * either be a child or group. The two positions are packed into a single
903     * long which can be unpacked using
904     * {@link #getPackedPositionChild(long)},
905     * {@link #getPackedPositionGroup(long)}, and
906     * {@link #getPackedPositionType(long)}.
907     *
908     * @param groupPosition The child's parent group's position.
909     * @param childPosition The child position within the group.
910     * @return The packed position representation of the child (and parent group).
911     */
912    public static long getPackedPositionForChild(int groupPosition, int childPosition) {
913        return (((long)PACKED_POSITION_TYPE_CHILD) << PACKED_POSITION_SHIFT_TYPE)
914                | ((((long)groupPosition) & PACKED_POSITION_INT_MASK_GROUP)
915                        << PACKED_POSITION_SHIFT_GROUP)
916                | (childPosition & PACKED_POSITION_INT_MASK_CHILD);
917    }
918
919    /**
920     * Returns the packed position representation of a group's position. See
921     * {@link #getPackedPositionForChild(int, int)}.
922     *
923     * @param groupPosition The child's parent group's position.
924     * @return The packed position representation of the group.
925     */
926    public static long getPackedPositionForGroup(int groupPosition) {
927        // No need to OR a type in because PACKED_POSITION_GROUP == 0
928        return ((((long)groupPosition) & PACKED_POSITION_INT_MASK_GROUP)
929                        << PACKED_POSITION_SHIFT_GROUP);
930    }
931
932    @Override
933    ContextMenuInfo createContextMenuInfo(View view, int flatListPosition, long id) {
934        if (isHeaderOrFooterPosition(flatListPosition)) {
935            // Return normal info for header/footer view context menus
936            return new AdapterContextMenuInfo(view, flatListPosition, id);
937        }
938
939        final int adjustedPosition = flatListPosition - getHeaderViewsCount();
940        PositionMetadata pm = mConnector.getUnflattenedPos(adjustedPosition);
941        ExpandableListPosition pos = pm.position;
942        pm.recycle();
943
944        id = getChildOrGroupId(pos);
945        long packedPosition = pos.getPackedPosition();
946        pos.recycle();
947
948        return new ExpandableListContextMenuInfo(view, packedPosition, id);
949    }
950
951    /**
952     * Gets the ID of the group or child at the given <code>position</code>.
953     * This is useful since there is no ListAdapter ID -> ExpandableListAdapter
954     * ID conversion mechanism (in some cases, it isn't possible).
955     *
956     * @param position The position of the child or group whose ID should be
957     *            returned.
958     */
959    private long getChildOrGroupId(ExpandableListPosition position) {
960        if (position.type == ExpandableListPosition.CHILD) {
961            return mAdapter.getChildId(position.groupPos, position.childPos);
962        } else {
963            return mAdapter.getGroupId(position.groupPos);
964        }
965    }
966
967    /**
968     * Sets the indicator to be drawn next to a child.
969     *
970     * @param childIndicator The drawable to be used as an indicator. If the
971     *            child is the last child for a group, the state
972     *            {@link android.R.attr#state_last} will be set.
973     */
974    public void setChildIndicator(Drawable childIndicator) {
975        mChildIndicator = childIndicator;
976    }
977
978    /**
979     * Sets the drawing bounds for the child indicator. For either, you can
980     * specify {@link #CHILD_INDICATOR_INHERIT} to use inherit from the general
981     * indicator's bounds.
982     *
983     * @see #setIndicatorBounds(int, int)
984     * @param left The left position (relative to the left bounds of this View)
985     *            to start drawing the indicator.
986     * @param right The right position (relative to the left bounds of this
987     *            View) to end the drawing of the indicator.
988     */
989    public void setChildIndicatorBounds(int left, int right) {
990        mChildIndicatorLeft = left;
991        mChildIndicatorRight = right;
992    }
993
994    /**
995     * Sets the indicator to be drawn next to a group.
996     *
997     * @param groupIndicator The drawable to be used as an indicator. If the
998     *            group is empty, the state {@link android.R.attr#state_empty} will be
999     *            set. If the group is expanded, the state
1000     *            {@link android.R.attr#state_expanded} will be set.
1001     */
1002    public void setGroupIndicator(Drawable groupIndicator) {
1003        mGroupIndicator = groupIndicator;
1004    }
1005
1006    /**
1007     * Sets the drawing bounds for the indicators (at minimum, the group indicator
1008     * is affected by this; the child indicator is affected by this if the
1009     * child indicator bounds are set to inherit).
1010     *
1011     * @see #setChildIndicatorBounds(int, int)
1012     * @param left The left position (relative to the left bounds of this View)
1013     *            to start drawing the indicator.
1014     * @param right The right position (relative to the left bounds of this
1015     *            View) to end the drawing of the indicator.
1016     */
1017    public void setIndicatorBounds(int left, int right) {
1018        mIndicatorLeft = left;
1019        mIndicatorRight = right;
1020    }
1021
1022    /**
1023     * Extra menu information specific to an {@link ExpandableListView} provided
1024     * to the
1025     * {@link android.view.View.OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo) }
1026     * callback when a context menu is brought up for this AdapterView.
1027     */
1028    public static class ExpandableListContextMenuInfo implements ContextMenu.ContextMenuInfo {
1029
1030        public ExpandableListContextMenuInfo(View targetView, long packedPosition, long id) {
1031            this.targetView = targetView;
1032            this.packedPosition = packedPosition;
1033            this.id = id;
1034        }
1035
1036        /**
1037         * The view for which the context menu is being displayed. This
1038         * will be one of the children Views of this {@link ExpandableListView}.
1039         */
1040        public View targetView;
1041
1042        /**
1043         * The packed position in the list represented by the adapter for which
1044         * the context menu is being displayed. Use the methods
1045         * {@link ExpandableListView#getPackedPositionType},
1046         * {@link ExpandableListView#getPackedPositionChild}, and
1047         * {@link ExpandableListView#getPackedPositionGroup} to unpack this.
1048         */
1049        public long packedPosition;
1050
1051        /**
1052         * The ID of the item (group or child) for which the context menu is
1053         * being displayed.
1054         */
1055        public long id;
1056    }
1057
1058    static class SavedState extends BaseSavedState {
1059        ArrayList<ExpandableListConnector.GroupMetadata> expandedGroupMetadataList;
1060
1061        /**
1062         * Constructor called from {@link ExpandableListView#onSaveInstanceState()}
1063         */
1064        SavedState(
1065                Parcelable superState,
1066                ArrayList<ExpandableListConnector.GroupMetadata> expandedGroupMetadataList) {
1067            super(superState);
1068            this.expandedGroupMetadataList = expandedGroupMetadataList;
1069        }
1070
1071        /**
1072         * Constructor called from {@link #CREATOR}
1073         */
1074        private SavedState(Parcel in) {
1075            super(in);
1076            expandedGroupMetadataList = new ArrayList<ExpandableListConnector.GroupMetadata>();
1077            in.readList(expandedGroupMetadataList, ExpandableListConnector.class.getClassLoader());
1078        }
1079
1080        @Override
1081        public void writeToParcel(Parcel out, int flags) {
1082            super.writeToParcel(out, flags);
1083            out.writeList(expandedGroupMetadataList);
1084        }
1085
1086        public static final Parcelable.Creator<SavedState> CREATOR
1087                = new Parcelable.Creator<SavedState>() {
1088            public SavedState createFromParcel(Parcel in) {
1089                return new SavedState(in);
1090            }
1091
1092            public SavedState[] newArray(int size) {
1093                return new SavedState[size];
1094            }
1095        };
1096    }
1097
1098    @Override
1099    public Parcelable onSaveInstanceState() {
1100        Parcelable superState = super.onSaveInstanceState();
1101        return new SavedState(superState,
1102                mConnector != null ? mConnector.getExpandedGroupMetadataList() : null);
1103    }
1104
1105    @Override
1106    public void onRestoreInstanceState(Parcelable state) {
1107        if (!(state instanceof SavedState)) {
1108            super.onRestoreInstanceState(state);
1109            return;
1110        }
1111
1112        SavedState ss = (SavedState) state;
1113        super.onRestoreInstanceState(ss.getSuperState());
1114
1115        if (mConnector != null && ss.expandedGroupMetadataList != null) {
1116            mConnector.setExpandedGroupMetadataList(ss.expandedGroupMetadataList);
1117        }
1118    }
1119
1120}
1121