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