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