blob: a4b20da1e2d31b360789e910f0a1a35a4c0948af [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.content.Context;
22import android.content.res.TypedArray;
23import android.graphics.Canvas;
24import android.graphics.Rect;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.graphics.drawable.ColorDrawable;
Adam Powell45803472010-01-25 15:10:44 -080026import android.graphics.drawable.Drawable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import 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
Adam Powell45803472010-01-25 15:10:44 -080036import java.util.ArrayList;
37
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038/**
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 @Override
486 public boolean performItemClick(View v, int position, long id) {
487 // Ignore clicks in header/footers
488 final int headerViewsCount = getHeaderViewsCount();
489 final int footerViewsStart = mItemCount - getFooterViewsCount();
490
491 if (position < headerViewsCount || position >= footerViewsStart) {
492 // Clicked on a header/footer, so ignore pass it on to super
493 return super.performItemClick(v, position, id);
494 }
495
496 // Internally handle the item click
497 return handleItemClick(v, position - headerViewsCount, id);
498 }
499
500 /**
501 * This will either expand/collapse groups (if a group was clicked) or pass
502 * on the click to the proper child (if a child was clicked)
503 *
504 * @param position The flat list position. This has already been factored to
505 * remove the header/footer.
506 * @param id The ListAdapter ID, not the group or child ID.
507 */
508 boolean handleItemClick(View v, int position, long id) {
509 final PositionMetadata posMetadata = mConnector.getUnflattenedPos(position);
510
511 id = getChildOrGroupId(posMetadata.position);
512
513 boolean returnValue;
514 if (posMetadata.position.type == ExpandableListPosition.GROUP) {
515 /* It's a group, so handle collapsing/expanding */
Romain Guy40395452009-12-04 16:51:52 -0800516
517 /* It's a group click, so pass on event */
518 if (mOnGroupClickListener != null) {
519 if (mOnGroupClickListener.onGroupClick(this, v,
520 posMetadata.position.groupPos, id)) {
521 posMetadata.recycle();
522 return true;
523 }
524 }
525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 if (posMetadata.isExpanded()) {
527 /* Collapse it */
528 mConnector.collapseGroup(posMetadata);
529
530 playSoundEffect(SoundEffectConstants.CLICK);
Romain Guy40395452009-12-04 16:51:52 -0800531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 if (mOnGroupCollapseListener != null) {
533 mOnGroupCollapseListener.onGroupCollapse(posMetadata.position.groupPos);
534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 /* Expand it */
537 mConnector.expandGroup(posMetadata);
538
539 playSoundEffect(SoundEffectConstants.CLICK);
Romain Guy40395452009-12-04 16:51:52 -0800540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 if (mOnGroupExpandListener != null) {
542 mOnGroupExpandListener.onGroupExpand(posMetadata.position.groupPos);
543 }
Adam Powell45803472010-01-25 15:10:44 -0800544
545 final int groupPos = posMetadata.position.groupPos;
546 final int groupFlatPos = posMetadata.position.flatListPos;
547
548 smoothScrollToPosition(groupFlatPos + mAdapter.getChildrenCount(groupPos),
549 groupFlatPos);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 }
Romain Guy40395452009-12-04 16:51:52 -0800551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 returnValue = true;
553 } else {
554 /* It's a child, so pass on event */
555 if (mOnChildClickListener != null) {
556 playSoundEffect(SoundEffectConstants.CLICK);
557 return mOnChildClickListener.onChildClick(this, v, posMetadata.position.groupPos,
558 posMetadata.position.childPos, id);
559 }
Romain Guy40395452009-12-04 16:51:52 -0800560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 returnValue = false;
562 }
Romain Guy40395452009-12-04 16:51:52 -0800563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 posMetadata.recycle();
Romain Guy40395452009-12-04 16:51:52 -0800565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 return returnValue;
567 }
568
569 /**
570 * Expand a group in the grouped list view
571 *
572 * @param groupPos the group to be expanded
573 * @return True if the group was expanded, false otherwise (if the group
574 * was already expanded, this will return false)
575 */
576 public boolean expandGroup(int groupPos) {
577 boolean retValue = mConnector.expandGroup(groupPos);
578
579 if (mOnGroupExpandListener != null) {
580 mOnGroupExpandListener.onGroupExpand(groupPos);
581 }
582
583 return retValue;
584 }
585
586 /**
587 * Collapse a group in the grouped list view
588 *
589 * @param groupPos position of the group to collapse
590 * @return True if the group was collapsed, false otherwise (if the group
591 * was already collapsed, this will return false)
592 */
593 public boolean collapseGroup(int groupPos) {
594 boolean retValue = mConnector.collapseGroup(groupPos);
595
596 if (mOnGroupCollapseListener != null) {
597 mOnGroupCollapseListener.onGroupCollapse(groupPos);
598 }
599
600 return retValue;
601 }
602
603 /** Used for being notified when a group is collapsed */
604 public interface OnGroupCollapseListener {
605 /**
606 * Callback method to be invoked when a group in this expandable list has
607 * been collapsed.
608 *
609 * @param groupPosition The group position that was collapsed
610 */
611 void onGroupCollapse(int groupPosition);
612 }
613
614 private OnGroupCollapseListener mOnGroupCollapseListener;
615
616 public void setOnGroupCollapseListener(
617 OnGroupCollapseListener onGroupCollapseListener) {
618 mOnGroupCollapseListener = onGroupCollapseListener;
619 }
620
621 /** Used for being notified when a group is expanded */
622 public interface OnGroupExpandListener {
623 /**
624 * Callback method to be invoked when a group in this expandable list has
625 * been expanded.
626 *
627 * @param groupPosition The group position that was expanded
628 */
629 void onGroupExpand(int groupPosition);
630 }
631
632 private OnGroupExpandListener mOnGroupExpandListener;
633
634 public void setOnGroupExpandListener(
635 OnGroupExpandListener onGroupExpandListener) {
636 mOnGroupExpandListener = onGroupExpandListener;
637 }
638
639 /**
640 * Interface definition for a callback to be invoked when a group in this
641 * expandable list has been clicked.
642 */
643 public interface OnGroupClickListener {
644 /**
645 * Callback method to be invoked when a group in this expandable list has
646 * been clicked.
647 *
648 * @param parent The ExpandableListConnector where the click happened
649 * @param v The view within the expandable list/ListView that was clicked
650 * @param groupPosition The group position that was clicked
651 * @param id The row id of the group that was clicked
652 * @return True if the click was handled
653 */
654 boolean onGroupClick(ExpandableListView parent, View v, int groupPosition,
655 long id);
656 }
657
658 private OnGroupClickListener mOnGroupClickListener;
659
660 public void setOnGroupClickListener(OnGroupClickListener onGroupClickListener) {
661 mOnGroupClickListener = onGroupClickListener;
662 }
663
664 /**
665 * Interface definition for a callback to be invoked when a child in this
666 * expandable list has been clicked.
667 */
668 public interface OnChildClickListener {
669 /**
670 * Callback method to be invoked when a child in this expandable list has
671 * been clicked.
672 *
673 * @param parent The ExpandableListView where the click happened
674 * @param v The view within the expandable list/ListView that was clicked
675 * @param groupPosition The group position that contains the child that
676 * was clicked
677 * @param childPosition The child position within the group
678 * @param id The row id of the child that was clicked
679 * @return True if the click was handled
680 */
681 boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
682 int childPosition, long id);
683 }
684
685 private OnChildClickListener mOnChildClickListener;
686
687 public void setOnChildClickListener(OnChildClickListener onChildClickListener) {
688 mOnChildClickListener = onChildClickListener;
689 }
690
691 /**
692 * Converts a flat list position (the raw position of an item (child or
693 * group) in the list) to an group and/or child position (represented in a
694 * packed position). This is useful in situations where the caller needs to
695 * use the underlying {@link ListView}'s methods. Use
696 * {@link ExpandableListView#getPackedPositionType} ,
697 * {@link ExpandableListView#getPackedPositionChild},
698 * {@link ExpandableListView#getPackedPositionGroup} to unpack.
699 *
700 * @param flatListPosition The flat list position to be converted.
701 * @return The group and/or child position for the given flat list position
702 * in packed position representation.
703 */
704 public long getExpandableListPosition(int flatListPosition) {
705 PositionMetadata pm = mConnector.getUnflattenedPos(flatListPosition);
706 long packedPos = pm.position.getPackedPosition();
707 pm.recycle();
708 return packedPos;
709 }
710
711 /**
712 * Converts a group and/or child position to a flat list position. This is
713 * useful in situations where the caller needs to use the underlying
714 * {@link ListView}'s methods.
715 *
716 * @param packedPosition The group and/or child positions to be converted in
717 * packed position representation. Use
718 * {@link #getPackedPositionForChild(int, int)} or
719 * {@link #getPackedPositionForGroup(int)}.
720 * @return The flat list position for the given child or group.
721 */
722 public int getFlatListPosition(long packedPosition) {
723 PositionMetadata pm = mConnector.getFlattenedPos(ExpandableListPosition
724 .obtainPosition(packedPosition));
725 int retValue = pm.position.flatListPos;
726 pm.recycle();
727 return retValue;
728 }
729
730 /**
731 * Gets the position of the currently selected group or child (along with
732 * its type). Can return {@link #PACKED_POSITION_VALUE_NULL} if no selection.
733 *
734 * @return A packed position containing the currently selected group or
735 * child's position and type. #PACKED_POSITION_VALUE_NULL if no selection.
736 */
737 public long getSelectedPosition() {
738 final int selectedPos = getSelectedItemPosition();
739 if (selectedPos == -1) return PACKED_POSITION_VALUE_NULL;
740
741 return getExpandableListPosition(selectedPos);
742 }
743
744 /**
745 * Gets the ID of the currently selected group or child. Can return -1 if no
746 * selection.
747 *
748 * @return The ID of the currently selected group or child. -1 if no
749 * selection.
750 */
751 public long getSelectedId() {
752 long packedPos = getSelectedPosition();
753 if (packedPos == PACKED_POSITION_VALUE_NULL) return -1;
754
755 int groupPos = getPackedPositionGroup(packedPos);
756
757 if (getPackedPositionType(packedPos) == PACKED_POSITION_TYPE_GROUP) {
758 // It's a group
759 return mAdapter.getGroupId(groupPos);
760 } else {
761 // It's a child
762 return mAdapter.getChildId(groupPos, getPackedPositionChild(packedPos));
763 }
764 }
765
766 /**
767 * Sets the selection to the specified group.
768 * @param groupPosition The position of the group that should be selected.
769 */
770 public void setSelectedGroup(int groupPosition) {
771 ExpandableListPosition elGroupPos = ExpandableListPosition
772 .obtainGroupPosition(groupPosition);
773 PositionMetadata pm = mConnector.getFlattenedPos(elGroupPos);
774 elGroupPos.recycle();
775 super.setSelection(pm.position.flatListPos);
776 pm.recycle();
777 }
778
779 /**
780 * Sets the selection to the specified child. If the child is in a collapsed
781 * group, the group will only be expanded and child subsequently selected if
782 * shouldExpandGroup is set to true, otherwise the method will return false.
783 *
784 * @param groupPosition The position of the group that contains the child.
785 * @param childPosition The position of the child within the group.
786 * @param shouldExpandGroup Whether the child's group should be expanded if
787 * it is collapsed.
788 * @return Whether the selection was successfully set on the child.
789 */
790 public boolean setSelectedChild(int groupPosition, int childPosition, boolean shouldExpandGroup) {
791 ExpandableListPosition elChildPos = ExpandableListPosition.obtainChildPosition(
792 groupPosition, childPosition);
793 PositionMetadata flatChildPos = mConnector.getFlattenedPos(elChildPos);
794
795 if (flatChildPos == null) {
796 // The child's group isn't expanded
797
798 // Shouldn't expand the group, so return false for we didn't set the selection
799 if (!shouldExpandGroup) return false;
800
801 expandGroup(groupPosition);
802
803 flatChildPos = mConnector.getFlattenedPos(elChildPos);
804
805 // Sanity check
806 if (flatChildPos == null) {
807 throw new IllegalStateException("Could not find child");
808 }
809 }
810
811 super.setSelection(flatChildPos.position.flatListPos);
812
813 elChildPos.recycle();
814 flatChildPos.recycle();
815
816 return true;
817 }
818
819 /**
820 * Whether the given group is currently expanded.
821 *
822 * @param groupPosition The group to check.
823 * @return Whether the group is currently expanded.
824 */
825 public boolean isGroupExpanded(int groupPosition) {
826 return mConnector.isGroupExpanded(groupPosition);
827 }
828
829 /**
830 * Gets the type of a packed position. See
831 * {@link #getPackedPositionForChild(int, int)}.
832 *
833 * @param packedPosition The packed position for which to return the type.
834 * @return The type of the position contained within the packed position,
835 * either {@link #PACKED_POSITION_TYPE_CHILD}, {@link #PACKED_POSITION_TYPE_GROUP}, or
836 * {@link #PACKED_POSITION_TYPE_NULL}.
837 */
838 public static int getPackedPositionType(long packedPosition) {
839 if (packedPosition == PACKED_POSITION_VALUE_NULL) {
840 return PACKED_POSITION_TYPE_NULL;
841 }
842
843 return (packedPosition & PACKED_POSITION_MASK_TYPE) == PACKED_POSITION_MASK_TYPE
844 ? PACKED_POSITION_TYPE_CHILD
845 : PACKED_POSITION_TYPE_GROUP;
846 }
847
848 /**
849 * Gets the group position from a packed position. See
850 * {@link #getPackedPositionForChild(int, int)}.
851 *
852 * @param packedPosition The packed position from which the group position
853 * will be returned.
854 * @return The group position portion of the packed position. If this does
855 * not contain a group, returns -1.
856 */
857 public static int getPackedPositionGroup(long packedPosition) {
858 // Null
859 if (packedPosition == PACKED_POSITION_VALUE_NULL) return -1;
860
861 return (int) ((packedPosition & PACKED_POSITION_MASK_GROUP) >> PACKED_POSITION_SHIFT_GROUP);
862 }
863
864 /**
865 * Gets the child position from a packed position that is of
866 * {@link #PACKED_POSITION_TYPE_CHILD} type (use {@link #getPackedPositionType(long)}).
867 * To get the group that this child belongs to, use
868 * {@link #getPackedPositionGroup(long)}. See
869 * {@link #getPackedPositionForChild(int, int)}.
870 *
871 * @param packedPosition The packed position from which the child position
872 * will be returned.
873 * @return The child position portion of the packed position. If this does
874 * not contain a child, returns -1.
875 */
876 public static int getPackedPositionChild(long packedPosition) {
877 // Null
878 if (packedPosition == PACKED_POSITION_VALUE_NULL) return -1;
879
880 // Group since a group type clears this bit
881 if ((packedPosition & PACKED_POSITION_MASK_TYPE) != PACKED_POSITION_MASK_TYPE) return -1;
882
883 return (int) (packedPosition & PACKED_POSITION_MASK_CHILD);
884 }
885
886 /**
887 * Returns the packed position representation of a child's position.
888 * <p>
889 * In general, a packed position should be used in
890 * situations where the position given to/returned from an
891 * {@link ExpandableListAdapter} or {@link ExpandableListView} method can
892 * either be a child or group. The two positions are packed into a single
893 * long which can be unpacked using
894 * {@link #getPackedPositionChild(long)},
895 * {@link #getPackedPositionGroup(long)}, and
896 * {@link #getPackedPositionType(long)}.
897 *
898 * @param groupPosition The child's parent group's position.
899 * @param childPosition The child position within the group.
900 * @return The packed position representation of the child (and parent group).
901 */
902 public static long getPackedPositionForChild(int groupPosition, int childPosition) {
903 return (((long)PACKED_POSITION_TYPE_CHILD) << PACKED_POSITION_SHIFT_TYPE)
904 | ((((long)groupPosition) & PACKED_POSITION_INT_MASK_GROUP)
905 << PACKED_POSITION_SHIFT_GROUP)
906 | (childPosition & PACKED_POSITION_INT_MASK_CHILD);
907 }
908
909 /**
910 * Returns the packed position representation of a group's position. See
911 * {@link #getPackedPositionForChild(int, int)}.
912 *
913 * @param groupPosition The child's parent group's position.
914 * @return The packed position representation of the group.
915 */
916 public static long getPackedPositionForGroup(int groupPosition) {
917 // No need to OR a type in because PACKED_POSITION_GROUP == 0
918 return ((((long)groupPosition) & PACKED_POSITION_INT_MASK_GROUP)
919 << PACKED_POSITION_SHIFT_GROUP);
920 }
921
922 @Override
923 ContextMenuInfo createContextMenuInfo(View view, int flatListPosition, long id) {
Jeff Sharkeyfd0d6272009-08-17 00:52:46 -0700924 // Adjust for and handle for header views
925 final int adjustedPosition = flatListPosition - getHeaderViewsCount();
926 if (adjustedPosition < 0) {
927 // Return normal info for header view context menus
928 return new AdapterContextMenuInfo(view, flatListPosition, id);
929 }
930
931 PositionMetadata pm = mConnector.getUnflattenedPos(adjustedPosition);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 ExpandableListPosition pos = pm.position;
933 pm.recycle();
934
935 id = getChildOrGroupId(pos);
936 long packedPosition = pos.getPackedPosition();
937 pos.recycle();
938
939 return new ExpandableListContextMenuInfo(view, packedPosition, id);
940 }
941
942 /**
943 * Gets the ID of the group or child at the given <code>position</code>.
944 * This is useful since there is no ListAdapter ID -> ExpandableListAdapter
945 * ID conversion mechanism (in some cases, it isn't possible).
946 *
947 * @param position The position of the child or group whose ID should be
948 * returned.
949 */
950 private long getChildOrGroupId(ExpandableListPosition position) {
951 if (position.type == ExpandableListPosition.CHILD) {
952 return mAdapter.getChildId(position.groupPos, position.childPos);
953 } else {
954 return mAdapter.getGroupId(position.groupPos);
955 }
956 }
957
958 /**
959 * Sets the indicator to be drawn next to a child.
960 *
961 * @param childIndicator The drawable to be used as an indicator. If the
962 * child is the last child for a group, the state
963 * {@link android.R.attr#state_last} will be set.
964 */
965 public void setChildIndicator(Drawable childIndicator) {
966 mChildIndicator = childIndicator;
967 }
968
969 /**
970 * Sets the drawing bounds for the child indicator. For either, you can
971 * specify {@link #CHILD_INDICATOR_INHERIT} to use inherit from the general
972 * indicator's bounds.
973 *
974 * @see #setIndicatorBounds(int, int)
975 * @param left The left position (relative to the left bounds of this View)
976 * to start drawing the indicator.
977 * @param right The right position (relative to the left bounds of this
978 * View) to end the drawing of the indicator.
979 */
980 public void setChildIndicatorBounds(int left, int right) {
981 mChildIndicatorLeft = left;
982 mChildIndicatorRight = right;
983 }
984
985 /**
986 * Sets the indicator to be drawn next to a group.
987 *
988 * @param groupIndicator The drawable to be used as an indicator. If the
989 * group is empty, the state {@link android.R.attr#state_empty} will be
990 * set. If the group is expanded, the state
991 * {@link android.R.attr#state_expanded} will be set.
992 */
993 public void setGroupIndicator(Drawable groupIndicator) {
994 mGroupIndicator = groupIndicator;
995 }
996
997 /**
998 * Sets the drawing bounds for the indicators (at minimum, the group indicator
999 * is affected by this; the child indicator is affected by this if the
1000 * child indicator bounds are set to inherit).
1001 *
1002 * @see #setChildIndicatorBounds(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 setIndicatorBounds(int left, int right) {
1009 mIndicatorLeft = left;
1010 mIndicatorRight = right;
1011 }
1012
1013 /**
1014 * Extra menu information specific to an {@link ExpandableListView} provided
1015 * to the
1016 * {@link android.view.View.OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo) }
1017 * callback when a context menu is brought up for this AdapterView.
1018 */
1019 public static class ExpandableListContextMenuInfo implements ContextMenu.ContextMenuInfo {
1020
1021 public ExpandableListContextMenuInfo(View targetView, long packedPosition, long id) {
1022 this.targetView = targetView;
1023 this.packedPosition = packedPosition;
1024 this.id = id;
1025 }
1026
1027 /**
1028 * The view for which the context menu is being displayed. This
1029 * will be one of the children Views of this {@link ExpandableListView}.
1030 */
1031 public View targetView;
1032
1033 /**
1034 * The packed position in the list represented by the adapter for which
1035 * the context menu is being displayed. Use the methods
1036 * {@link ExpandableListView#getPackedPositionType},
1037 * {@link ExpandableListView#getPackedPositionChild}, and
1038 * {@link ExpandableListView#getPackedPositionGroup} to unpack this.
1039 */
1040 public long packedPosition;
1041
1042 /**
1043 * The ID of the item (group or child) for which the context menu is
1044 * being displayed.
1045 */
1046 public long id;
1047 }
1048
1049 static class SavedState extends BaseSavedState {
1050 ArrayList<ExpandableListConnector.GroupMetadata> expandedGroupMetadataList;
1051
1052 /**
1053 * Constructor called from {@link ExpandableListView#onSaveInstanceState()}
1054 */
1055 SavedState(
1056 Parcelable superState,
1057 ArrayList<ExpandableListConnector.GroupMetadata> expandedGroupMetadataList) {
1058 super(superState);
1059 this.expandedGroupMetadataList = expandedGroupMetadataList;
1060 }
1061
1062 /**
1063 * Constructor called from {@link #CREATOR}
1064 */
1065 private SavedState(Parcel in) {
1066 super(in);
1067 expandedGroupMetadataList = new ArrayList<ExpandableListConnector.GroupMetadata>();
1068 in.readList(expandedGroupMetadataList, ExpandableListConnector.class.getClassLoader());
1069 }
1070
1071 @Override
1072 public void writeToParcel(Parcel out, int flags) {
1073 super.writeToParcel(out, flags);
1074 out.writeList(expandedGroupMetadataList);
1075 }
1076
1077 public static final Parcelable.Creator<SavedState> CREATOR
1078 = new Parcelable.Creator<SavedState>() {
1079 public SavedState createFromParcel(Parcel in) {
1080 return new SavedState(in);
1081 }
1082
1083 public SavedState[] newArray(int size) {
1084 return new SavedState[size];
1085 }
1086 };
1087 }
1088
1089 @Override
1090 public Parcelable onSaveInstanceState() {
1091 Parcelable superState = super.onSaveInstanceState();
1092 return new SavedState(superState,
1093 mConnector != null ? mConnector.getExpandedGroupMetadataList() : null);
1094 }
1095
1096 @Override
1097 public void onRestoreInstanceState(Parcelable state) {
Romain Guy7444e142009-05-21 12:54:16 -07001098 if (!(state instanceof SavedState)) {
1099 super.onRestoreInstanceState(state);
1100 return;
1101 }
1102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 SavedState ss = (SavedState) state;
1104 super.onRestoreInstanceState(ss.getSuperState());
1105
1106 if (mConnector != null && ss.expandedGroupMetadataList != null) {
1107 mConnector.setExpandedGroupMetadataList(ss.expandedGroupMetadataList);
1108 }
1109 }
1110
1111}