blob: 51a1ef26d4af6f259bba5cccb7e381384ffd9a00 [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
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -080019import com.android.internal.R;
20import com.google.android.collect.Lists;
21
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.Context;
23import android.content.res.TypedArray;
24import android.graphics.Canvas;
Romain Guy8f1344f2009-05-15 16:03:59 -070025import android.graphics.Paint;
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -080026import android.graphics.PixelFormat;
27import android.graphics.Rect;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.graphics.drawable.ColorDrawable;
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -080029import android.graphics.drawable.Drawable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.os.Parcel;
31import android.os.Parcelable;
32import android.util.AttributeSet;
33import android.util.SparseBooleanArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.view.FocusFinder;
35import android.view.KeyEvent;
36import android.view.MotionEvent;
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -080037import android.view.SoundEffectConstants;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.view.View;
39import android.view.ViewDebug;
40import android.view.ViewGroup;
41import android.view.ViewParent;
svetoslavganov75986cf2009-05-14 22:28:01 -070042import android.view.accessibility.AccessibilityEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import java.util.ArrayList;
45
46/*
47 * Implementation Notes:
48 *
49 * Some terminology:
50 *
51 * index - index of the items that are currently visible
52 * position - index of the items in the cursor
53 */
54
55
56/**
57 * A view that shows items in a vertically scrolling list. The items
58 * come from the {@link ListAdapter} associated with this view.
59 *
60 * @attr ref android.R.styleable#ListView_entries
61 * @attr ref android.R.styleable#ListView_divider
62 * @attr ref android.R.styleable#ListView_dividerHeight
63 * @attr ref android.R.styleable#ListView_choiceMode
64 * @attr ref android.R.styleable#ListView_headerDividersEnabled
65 * @attr ref android.R.styleable#ListView_footerDividersEnabled
66 */
67public class ListView extends AbsListView {
68 /**
69 * Used to indicate a no preference for a position type.
70 */
71 static final int NO_POSITION = -1;
72
73 /**
74 * Normal list that does not indicate choices
75 */
76 public static final int CHOICE_MODE_NONE = 0;
77
78 /**
79 * The list allows up to one choice
80 */
81 public static final int CHOICE_MODE_SINGLE = 1;
82
83 /**
84 * The list allows multiple choices
85 */
86 public static final int CHOICE_MODE_MULTIPLE = 2;
87
88 /**
89 * When arrow scrolling, ListView will never scroll more than this factor
90 * times the height of the list.
91 */
92 private static final float MAX_SCROLL_FACTOR = 0.33f;
93
94 /**
95 * When arrow scrolling, need a certain amount of pixels to preview next
96 * items. This is usually the fading edge, but if that is small enough,
97 * we want to make sure we preview at least this many pixels.
98 */
99 private static final int MIN_SCROLL_PREVIEW_PIXELS = 2;
100
101 /**
102 * A class that represents a fixed view in a list, for example a header at the top
103 * or a footer at the bottom.
104 */
105 public class FixedViewInfo {
106 /** The view to add to the list */
107 public View view;
108 /** The data backing the view. This is returned from {@link ListAdapter#getItem(int)}. */
109 public Object data;
110 /** <code>true</code> if the fixed view should be selectable in the list */
111 public boolean isSelectable;
112 }
113
114 private ArrayList<FixedViewInfo> mHeaderViewInfos = Lists.newArrayList();
115 private ArrayList<FixedViewInfo> mFooterViewInfos = Lists.newArrayList();
116
117 Drawable mDivider;
118 int mDividerHeight;
Romain Guy24443ea2009-05-11 11:56:30 -0700119
120 private boolean mIsCacheColorOpaque;
121 private boolean mDividerIsOpaque;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 private boolean mClipDivider;
Romain Guy24443ea2009-05-11 11:56:30 -0700123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 private boolean mHeaderDividersEnabled;
125 private boolean mFooterDividersEnabled;
126
127 private boolean mAreAllItemsSelectable = true;
128
129 private boolean mItemsCanFocus = false;
130
131 private int mChoiceMode = CHOICE_MODE_NONE;
132
133 private SparseBooleanArray mCheckStates;
134
135 // used for temporary calculations.
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700136 private final Rect mTempRect = new Rect();
Romain Guya02903f2009-05-23 13:26:46 -0700137 private Paint mDividerPaint;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138
139 // the single allocated result per list view; kinda cheesey but avoids
140 // allocating these thingies too often.
141 private ArrowScrollFocusResult mArrowScrollFocusResult = new ArrowScrollFocusResult();
142
143 public ListView(Context context) {
144 this(context, null);
145 }
146
147 public ListView(Context context, AttributeSet attrs) {
148 this(context, attrs, com.android.internal.R.attr.listViewStyle);
149 }
150
151 public ListView(Context context, AttributeSet attrs, int defStyle) {
152 super(context, attrs, defStyle);
153
154 TypedArray a = context.obtainStyledAttributes(attrs,
155 com.android.internal.R.styleable.ListView, defStyle, 0);
156
157 CharSequence[] entries = a.getTextArray(
158 com.android.internal.R.styleable.ListView_entries);
159 if (entries != null) {
160 setAdapter(new ArrayAdapter<CharSequence>(context,
161 com.android.internal.R.layout.simple_list_item_1, entries));
162 }
163
164 final Drawable d = a.getDrawable(com.android.internal.R.styleable.ListView_divider);
165 if (d != null) {
166 // If a divider is specified use its intrinsic height for divider height
167 setDivider(d);
168 }
169
170 // Use the height specified, zero being the default
171 final int dividerHeight = a.getDimensionPixelSize(
172 com.android.internal.R.styleable.ListView_dividerHeight, 0);
173 if (dividerHeight != 0) {
174 setDividerHeight(dividerHeight);
175 }
176
Romain Guy536fb042009-06-17 17:01:04 -0700177 setChoiceMode(a.getInt(R.styleable.ListView_choiceMode, CHOICE_MODE_NONE));
178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 mHeaderDividersEnabled = a.getBoolean(R.styleable.ListView_headerDividersEnabled, true);
180 mFooterDividersEnabled = a.getBoolean(R.styleable.ListView_footerDividersEnabled, true);
181
182 a.recycle();
183 }
184
185 /**
186 * @return The maximum amount a list view will scroll in response to
187 * an arrow event.
188 */
189 public int getMaxScrollAmount() {
190 return (int) (MAX_SCROLL_FACTOR * (mBottom - mTop));
191 }
192
193 /**
194 * Make sure views are touching the top or bottom edge, as appropriate for
195 * our gravity
196 */
197 private void adjustViewsUpOrDown() {
198 final int childCount = getChildCount();
199 int delta;
200
201 if (childCount > 0) {
202 View child;
203
204 if (!mStackFromBottom) {
205 // Uh-oh -- we came up short. Slide all views up to make them
206 // align with the top
207 child = getChildAt(0);
208 delta = child.getTop() - mListPadding.top;
209 if (mFirstPosition != 0) {
210 // It's OK to have some space above the first item if it is
211 // part of the vertical spacing
212 delta -= mDividerHeight;
213 }
214 if (delta < 0) {
215 // We only are looking to see if we are too low, not too high
216 delta = 0;
217 }
218 } else {
219 // we are too high, slide all views down to align with bottom
220 child = getChildAt(childCount - 1);
221 delta = child.getBottom() - (getHeight() - mListPadding.bottom);
222
223 if (mFirstPosition + childCount < mItemCount) {
224 // It's OK to have some space below the last item if it is
225 // part of the vertical spacing
226 delta += mDividerHeight;
227 }
228
229 if (delta > 0) {
230 delta = 0;
231 }
232 }
233
234 if (delta != 0) {
235 offsetChildrenTopAndBottom(-delta);
236 }
237 }
238 }
239
240 /**
241 * Add a fixed view to appear at the top of the list. If addHeaderView is
242 * called more than once, the views will appear in the order they were
243 * added. Views added using this call can take focus if they want.
244 * <p>
245 * NOTE: Call this before calling setAdapter. This is so ListView can wrap
246 * the supplied cursor with one that that will also account for header
247 * views.
248 *
249 * @param v The view to add.
250 * @param data Data to associate with this view
251 * @param isSelectable whether the item is selectable
252 */
253 public void addHeaderView(View v, Object data, boolean isSelectable) {
254
255 if (mAdapter != null) {
256 throw new IllegalStateException(
257 "Cannot add header view to list -- setAdapter has already been called.");
258 }
259
260 FixedViewInfo info = new FixedViewInfo();
261 info.view = v;
262 info.data = data;
263 info.isSelectable = isSelectable;
264 mHeaderViewInfos.add(info);
265 }
266
267 /**
268 * Add a fixed view to appear at the top of the list. If addHeaderView is
269 * called more than once, the views will appear in the order they were
270 * added. Views added using this call can take focus if they want.
271 * <p>
272 * NOTE: Call this before calling setAdapter. This is so ListView can wrap
273 * the supplied cursor with one that that will also account for header
274 * views.
275 *
276 * @param v The view to add.
277 */
278 public void addHeaderView(View v) {
279 addHeaderView(v, null, true);
280 }
281
282 @Override
283 public int getHeaderViewsCount() {
284 return mHeaderViewInfos.size();
285 }
286
287 /**
288 * Removes a previously-added header view.
289 *
290 * @param v The view to remove
291 * @return true if the view was removed, false if the view was not a header
292 * view
293 */
294 public boolean removeHeaderView(View v) {
295 if (mHeaderViewInfos.size() > 0) {
296 boolean result = false;
297 if (((HeaderViewListAdapter) mAdapter).removeHeader(v)) {
298 mDataSetObserver.onChanged();
299 result = true;
300 }
301 removeFixedViewInfo(v, mHeaderViewInfos);
302 return result;
303 }
304 return false;
305 }
306
307 private void removeFixedViewInfo(View v, ArrayList<FixedViewInfo> where) {
308 int len = where.size();
309 for (int i = 0; i < len; ++i) {
310 FixedViewInfo info = where.get(i);
311 if (info.view == v) {
312 where.remove(i);
313 break;
314 }
315 }
316 }
317
318 /**
319 * Add a fixed view to appear at the bottom of the list. If addFooterView is
320 * called more than once, the views will appear in the order they were
321 * added. Views added using this call can take focus if they want.
322 * <p>
323 * NOTE: Call this before calling setAdapter. This is so ListView can wrap
324 * the supplied cursor with one that that will also account for header
325 * views.
326 *
327 * @param v The view to add.
328 * @param data Data to associate with this view
329 * @param isSelectable true if the footer view can be selected
330 */
331 public void addFooterView(View v, Object data, boolean isSelectable) {
332 FixedViewInfo info = new FixedViewInfo();
333 info.view = v;
334 info.data = data;
335 info.isSelectable = isSelectable;
336 mFooterViewInfos.add(info);
337
338 // in the case of re-adding a footer view, or adding one later on,
339 // we need to notify the observer
340 if (mDataSetObserver != null) {
341 mDataSetObserver.onChanged();
342 }
343 }
344
345 /**
346 * Add a fixed view to appear at the bottom of the list. If addFooterView is called more
347 * than once, the views will appear in the order they were added. Views added using
348 * this call can take focus if they want.
349 * <p>NOTE: Call this before calling setAdapter. This is so ListView can wrap the supplied
350 * cursor with one that that will also account for header views.
351 *
352 *
353 * @param v The view to add.
354 */
355 public void addFooterView(View v) {
356 addFooterView(v, null, true);
357 }
358
359 @Override
360 public int getFooterViewsCount() {
361 return mFooterViewInfos.size();
362 }
363
364 /**
365 * Removes a previously-added footer view.
366 *
367 * @param v The view to remove
368 * @return
369 * true if the view was removed, false if the view was not a footer view
370 */
371 public boolean removeFooterView(View v) {
372 if (mFooterViewInfos.size() > 0) {
373 boolean result = false;
374 if (((HeaderViewListAdapter) mAdapter).removeFooter(v)) {
375 mDataSetObserver.onChanged();
376 result = true;
377 }
378 removeFixedViewInfo(v, mFooterViewInfos);
379 return result;
380 }
381 return false;
382 }
383
384 /**
385 * Returns the adapter currently in use in this ListView. The returned adapter
386 * might not be the same adapter passed to {@link #setAdapter(ListAdapter)} but
387 * might be a {@link WrapperListAdapter}.
388 *
389 * @return The adapter currently used to display data in this ListView.
390 *
391 * @see #setAdapter(ListAdapter)
392 */
393 @Override
394 public ListAdapter getAdapter() {
395 return mAdapter;
396 }
397
398 /**
399 * Sets the data behind this ListView.
400 *
401 * The adapter passed to this method may be wrapped by a {@link WrapperListAdapter},
402 * depending on the ListView features currently in use. For instance, adding
403 * headers and/or footers will cause the adapter to be wrapped.
404 *
405 * @param adapter The ListAdapter which is responsible for maintaining the
406 * data backing this list and for producing a view to represent an
407 * item in that data set.
408 *
409 * @see #getAdapter()
410 */
411 @Override
412 public void setAdapter(ListAdapter adapter) {
413 if (null != mAdapter) {
414 mAdapter.unregisterDataSetObserver(mDataSetObserver);
415 }
416
417 resetList();
418 mRecycler.clear();
419
420 if (mHeaderViewInfos.size() > 0|| mFooterViewInfos.size() > 0) {
421 mAdapter = new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, adapter);
422 } else {
423 mAdapter = adapter;
424 }
425
426 mOldSelectedPosition = INVALID_POSITION;
427 mOldSelectedRowId = INVALID_ROW_ID;
428 if (mAdapter != null) {
429 mAreAllItemsSelectable = mAdapter.areAllItemsEnabled();
430 mOldItemCount = mItemCount;
431 mItemCount = mAdapter.getCount();
432 checkFocus();
433
434 mDataSetObserver = new AdapterDataSetObserver();
435 mAdapter.registerDataSetObserver(mDataSetObserver);
436
437 mRecycler.setViewTypeCount(mAdapter.getViewTypeCount());
438
439 int position;
440 if (mStackFromBottom) {
441 position = lookForSelectablePosition(mItemCount - 1, false);
442 } else {
443 position = lookForSelectablePosition(0, true);
444 }
445 setSelectedPositionInt(position);
446 setNextSelectedPositionInt(position);
447
448 if (mItemCount == 0) {
449 // Nothing selected
450 checkSelectionChanged();
451 }
452
453 } else {
454 mAreAllItemsSelectable = true;
455 checkFocus();
456 // Nothing selected
457 checkSelectionChanged();
458 }
459
460 if (mCheckStates != null) {
461 mCheckStates.clear();
462 }
463
464 requestLayout();
465 }
466
467
468 /**
469 * The list is empty. Clear everything out.
470 */
471 @Override
472 void resetList() {
Romain Guy2e447d42009-04-28 18:01:24 -0700473 // The parent's resetList() will remove all views from the layout so we need to
474 // cleanup the state of our footers and headers
475 clearRecycledState(mHeaderViewInfos);
476 clearRecycledState(mFooterViewInfos);
477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 super.resetList();
Romain Guy2e447d42009-04-28 18:01:24 -0700479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 mLayoutMode = LAYOUT_NORMAL;
481 }
482
Romain Guy2e447d42009-04-28 18:01:24 -0700483 private void clearRecycledState(ArrayList<FixedViewInfo> infos) {
484 if (infos != null) {
485 final int count = infos.size();
486
487 for (int i = 0; i < count; i++) {
488 final View child = infos.get(i).view;
489 final LayoutParams p = (LayoutParams) child.getLayoutParams();
490 if (p != null) {
491 p.recycledHeaderFooter = false;
492 }
493 }
494 }
495 }
496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 /**
498 * @return Whether the list needs to show the top fading edge
499 */
500 private boolean showingTopFadingEdge() {
501 final int listTop = mScrollY + mListPadding.top;
502 return (mFirstPosition > 0) || (getChildAt(0).getTop() > listTop);
503 }
504
505 /**
506 * @return Whether the list needs to show the bottom fading edge
507 */
508 private boolean showingBottomFadingEdge() {
509 final int childCount = getChildCount();
510 final int bottomOfBottomChild = getChildAt(childCount - 1).getBottom();
511 final int lastVisiblePosition = mFirstPosition + childCount - 1;
512
513 final int listBottom = mScrollY + getHeight() - mListPadding.bottom;
514
515 return (lastVisiblePosition < mItemCount - 1)
516 || (bottomOfBottomChild < listBottom);
517 }
518
519
520 @Override
521 public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) {
522
523 int rectTopWithinChild = rect.top;
524
525 // offset so rect is in coordinates of the this view
526 rect.offset(child.getLeft(), child.getTop());
527 rect.offset(-child.getScrollX(), -child.getScrollY());
528
529 final int height = getHeight();
530 int listUnfadedTop = getScrollY();
531 int listUnfadedBottom = listUnfadedTop + height;
532 final int fadingEdge = getVerticalFadingEdgeLength();
533
534 if (showingTopFadingEdge()) {
535 // leave room for top fading edge as long as rect isn't at very top
536 if ((mSelectedPosition > 0) || (rectTopWithinChild > fadingEdge)) {
537 listUnfadedTop += fadingEdge;
538 }
539 }
540
541 int childCount = getChildCount();
542 int bottomOfBottomChild = getChildAt(childCount - 1).getBottom();
543
544 if (showingBottomFadingEdge()) {
545 // leave room for bottom fading edge as long as rect isn't at very bottom
546 if ((mSelectedPosition < mItemCount - 1)
547 || (rect.bottom < (bottomOfBottomChild - fadingEdge))) {
548 listUnfadedBottom -= fadingEdge;
549 }
550 }
551
552 int scrollYDelta = 0;
553
554 if (rect.bottom > listUnfadedBottom && rect.top > listUnfadedTop) {
555 // need to MOVE DOWN to get it in view: move down just enough so
556 // that the entire rectangle is in view (or at least the first
557 // screen size chunk).
558
559 if (rect.height() > height) {
560 // just enough to get screen size chunk on
561 scrollYDelta += (rect.top - listUnfadedTop);
562 } else {
563 // get entire rect at bottom of screen
564 scrollYDelta += (rect.bottom - listUnfadedBottom);
565 }
566
567 // make sure we aren't scrolling beyond the end of our children
568 int distanceToBottom = bottomOfBottomChild - listUnfadedBottom;
569 scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
570 } else if (rect.top < listUnfadedTop && rect.bottom < listUnfadedBottom) {
571 // need to MOVE UP to get it in view: move up just enough so that
572 // entire rectangle is in view (or at least the first screen
573 // size chunk of it).
574
575 if (rect.height() > height) {
576 // screen size chunk
577 scrollYDelta -= (listUnfadedBottom - rect.bottom);
578 } else {
579 // entire rect at top
580 scrollYDelta -= (listUnfadedTop - rect.top);
581 }
582
583 // make sure we aren't scrolling any further than the top our children
584 int top = getChildAt(0).getTop();
585 int deltaToTop = top - listUnfadedTop;
586 scrollYDelta = Math.max(scrollYDelta, deltaToTop);
587 }
588
589 final boolean scroll = scrollYDelta != 0;
590 if (scroll) {
591 scrollListItemsBy(-scrollYDelta);
592 positionSelector(child);
593 mSelectedTop = child.getTop();
594 invalidate();
595 }
596 return scroll;
597 }
598
599 /**
600 * {@inheritDoc}
601 */
602 @Override
603 void fillGap(boolean down) {
604 final int count = getChildCount();
605 if (down) {
606 final int startOffset = count > 0 ? getChildAt(count - 1).getBottom() + mDividerHeight :
607 getListPaddingTop();
608 fillDown(mFirstPosition + count, startOffset);
609 correctTooHigh(getChildCount());
610 } else {
611 final int startOffset = count > 0 ? getChildAt(0).getTop() - mDividerHeight :
612 getHeight() - getListPaddingBottom();
613 fillUp(mFirstPosition - 1, startOffset);
614 correctTooLow(getChildCount());
615 }
616 }
617
618 /**
619 * Fills the list from pos down to the end of the list view.
620 *
621 * @param pos The first position to put in the list
622 *
623 * @param nextTop The location where the top of the item associated with pos
624 * should be drawn
625 *
626 * @return The view that is currently selected, if it happens to be in the
627 * range that we draw.
628 */
629 private View fillDown(int pos, int nextTop) {
630 View selectedView = null;
631
632 int end = (mBottom - mTop) - mListPadding.bottom;
633
634 while (nextTop < end && pos < mItemCount) {
635 // is this the selected item?
636 boolean selected = pos == mSelectedPosition;
637 View child = makeAndAddView(pos, nextTop, true, mListPadding.left, selected);
638
639 nextTop = child.getBottom() + mDividerHeight;
640 if (selected) {
641 selectedView = child;
642 }
643 pos++;
644 }
645
646 return selectedView;
647 }
648
649 /**
650 * Fills the list from pos up to the top of the list view.
651 *
652 * @param pos The first position to put in the list
653 *
654 * @param nextBottom The location where the bottom of the item associated
655 * with pos should be drawn
656 *
657 * @return The view that is currently selected
658 */
659 private View fillUp(int pos, int nextBottom) {
660 View selectedView = null;
661
662 int end = mListPadding.top;
663
664 while (nextBottom > end && pos >= 0) {
665 // is this the selected item?
666 boolean selected = pos == mSelectedPosition;
667 View child = makeAndAddView(pos, nextBottom, false, mListPadding.left, selected);
668 nextBottom = child.getTop() - mDividerHeight;
669 if (selected) {
670 selectedView = child;
671 }
672 pos--;
673 }
674
675 mFirstPosition = pos + 1;
676
677 return selectedView;
678 }
679
680 /**
681 * Fills the list from top to bottom, starting with mFirstPosition
682 *
683 * @param nextTop The location where the top of the first item should be
684 * drawn
685 *
686 * @return The view that is currently selected
687 */
688 private View fillFromTop(int nextTop) {
689 mFirstPosition = Math.min(mFirstPosition, mSelectedPosition);
690 mFirstPosition = Math.min(mFirstPosition, mItemCount - 1);
691 if (mFirstPosition < 0) {
692 mFirstPosition = 0;
693 }
694 return fillDown(mFirstPosition, nextTop);
695 }
696
697
698 /**
699 * Put mSelectedPosition in the middle of the screen and then build up and
700 * down from there. This method forces mSelectedPosition to the center.
701 *
702 * @param childrenTop Top of the area in which children can be drawn, as
703 * measured in pixels
704 * @param childrenBottom Bottom of the area in which children can be drawn,
705 * as measured in pixels
706 * @return Currently selected view
707 */
708 private View fillFromMiddle(int childrenTop, int childrenBottom) {
709 int height = childrenBottom - childrenTop;
710
711 int position = reconcileSelectedPosition();
712
713 View sel = makeAndAddView(position, childrenTop, true,
714 mListPadding.left, true);
715 mFirstPosition = position;
716
717 int selHeight = sel.getMeasuredHeight();
718 if (selHeight <= height) {
719 sel.offsetTopAndBottom((height - selHeight) / 2);
720 }
721
722 fillAboveAndBelow(sel, position);
723
724 if (!mStackFromBottom) {
725 correctTooHigh(getChildCount());
726 } else {
727 correctTooLow(getChildCount());
728 }
729
730 return sel;
731 }
732
733 /**
734 * Once the selected view as been placed, fill up the visible area above and
735 * below it.
736 *
737 * @param sel The selected view
738 * @param position The position corresponding to sel
739 */
740 private void fillAboveAndBelow(View sel, int position) {
741 final int dividerHeight = mDividerHeight;
742 if (!mStackFromBottom) {
743 fillUp(position - 1, sel.getTop() - dividerHeight);
744 adjustViewsUpOrDown();
745 fillDown(position + 1, sel.getBottom() + dividerHeight);
746 } else {
747 fillDown(position + 1, sel.getBottom() + dividerHeight);
748 adjustViewsUpOrDown();
749 fillUp(position - 1, sel.getTop() - dividerHeight);
750 }
751 }
752
753
754 /**
755 * Fills the grid based on positioning the new selection at a specific
756 * location. The selection may be moved so that it does not intersect the
757 * faded edges. The grid is then filled upwards and downwards from there.
758 *
759 * @param selectedTop Where the selected item should be
760 * @param childrenTop Where to start drawing children
761 * @param childrenBottom Last pixel where children can be drawn
762 * @return The view that currently has selection
763 */
764 private View fillFromSelection(int selectedTop, int childrenTop, int childrenBottom) {
765 int fadingEdgeLength = getVerticalFadingEdgeLength();
766 final int selectedPosition = mSelectedPosition;
767
768 View sel;
769
770 final int topSelectionPixel = getTopSelectionPixel(childrenTop, fadingEdgeLength,
771 selectedPosition);
772 final int bottomSelectionPixel = getBottomSelectionPixel(childrenBottom, fadingEdgeLength,
773 selectedPosition);
774
775 sel = makeAndAddView(selectedPosition, selectedTop, true, mListPadding.left, true);
776
777
778 // Some of the newly selected item extends below the bottom of the list
779 if (sel.getBottom() > bottomSelectionPixel) {
780 // Find space available above the selection into which we can scroll
781 // upwards
782 final int spaceAbove = sel.getTop() - topSelectionPixel;
783
784 // Find space required to bring the bottom of the selected item
785 // fully into view
786 final int spaceBelow = sel.getBottom() - bottomSelectionPixel;
787 final int offset = Math.min(spaceAbove, spaceBelow);
788
789 // Now offset the selected item to get it into view
790 sel.offsetTopAndBottom(-offset);
791 } else if (sel.getTop() < topSelectionPixel) {
792 // Find space required to bring the top of the selected item fully
793 // into view
794 final int spaceAbove = topSelectionPixel - sel.getTop();
795
796 // Find space available below the selection into which we can scroll
797 // downwards
798 final int spaceBelow = bottomSelectionPixel - sel.getBottom();
799 final int offset = Math.min(spaceAbove, spaceBelow);
800
801 // Offset the selected item to get it into view
802 sel.offsetTopAndBottom(offset);
803 }
804
805 // Fill in views above and below
806 fillAboveAndBelow(sel, selectedPosition);
807
808 if (!mStackFromBottom) {
809 correctTooHigh(getChildCount());
810 } else {
811 correctTooLow(getChildCount());
812 }
813
814 return sel;
815 }
816
817 /**
818 * Calculate the bottom-most pixel we can draw the selection into
819 *
820 * @param childrenBottom Bottom pixel were children can be drawn
821 * @param fadingEdgeLength Length of the fading edge in pixels, if present
822 * @param selectedPosition The position that will be selected
823 * @return The bottom-most pixel we can draw the selection into
824 */
825 private int getBottomSelectionPixel(int childrenBottom, int fadingEdgeLength,
826 int selectedPosition) {
827 int bottomSelectionPixel = childrenBottom;
828 if (selectedPosition != mItemCount - 1) {
829 bottomSelectionPixel -= fadingEdgeLength;
830 }
831 return bottomSelectionPixel;
832 }
833
834 /**
835 * Calculate the top-most pixel we can draw the selection into
836 *
837 * @param childrenTop Top pixel were children can be drawn
838 * @param fadingEdgeLength Length of the fading edge in pixels, if present
839 * @param selectedPosition The position that will be selected
840 * @return The top-most pixel we can draw the selection into
841 */
842 private int getTopSelectionPixel(int childrenTop, int fadingEdgeLength, int selectedPosition) {
843 // first pixel we can draw the selection into
844 int topSelectionPixel = childrenTop;
845 if (selectedPosition > 0) {
846 topSelectionPixel += fadingEdgeLength;
847 }
848 return topSelectionPixel;
849 }
850
851
852 /**
853 * Fills the list based on positioning the new selection relative to the old
854 * selection. The new selection will be placed at, above, or below the
855 * location of the new selection depending on how the selection is moving.
856 * The selection will then be pinned to the visible part of the screen,
857 * excluding the edges that are faded. The list is then filled upwards and
858 * downwards from there.
859 *
860 * @param oldSel The old selected view. Useful for trying to put the new
861 * selection in the same place
862 * @param newSel The view that is to become selected. Useful for trying to
863 * put the new selection in the same place
864 * @param delta Which way we are moving
865 * @param childrenTop Where to start drawing children
866 * @param childrenBottom Last pixel where children can be drawn
867 * @return The view that currently has selection
868 */
869 private View moveSelection(View oldSel, View newSel, int delta, int childrenTop,
870 int childrenBottom) {
871 int fadingEdgeLength = getVerticalFadingEdgeLength();
872 final int selectedPosition = mSelectedPosition;
873
874 View sel;
875
876 final int topSelectionPixel = getTopSelectionPixel(childrenTop, fadingEdgeLength,
877 selectedPosition);
878 final int bottomSelectionPixel = getBottomSelectionPixel(childrenTop, fadingEdgeLength,
879 selectedPosition);
880
881 if (delta > 0) {
882 /*
883 * Case 1: Scrolling down.
884 */
885
886 /*
887 * Before After
888 * | | | |
889 * +-------+ +-------+
890 * | A | | A |
891 * | 1 | => +-------+
892 * +-------+ | B |
893 * | B | | 2 |
894 * +-------+ +-------+
895 * | | | |
896 *
897 * Try to keep the top of the previously selected item where it was.
898 * oldSel = A
899 * sel = B
900 */
901
902 // Put oldSel (A) where it belongs
903 oldSel = makeAndAddView(selectedPosition - 1, oldSel.getTop(), true,
904 mListPadding.left, false);
905
906 final int dividerHeight = mDividerHeight;
907
908 // Now put the new selection (B) below that
909 sel = makeAndAddView(selectedPosition, oldSel.getBottom() + dividerHeight, true,
910 mListPadding.left, true);
911
912 // Some of the newly selected item extends below the bottom of the list
913 if (sel.getBottom() > bottomSelectionPixel) {
914
915 // Find space available above the selection into which we can scroll upwards
916 int spaceAbove = sel.getTop() - topSelectionPixel;
917
918 // Find space required to bring the bottom of the selected item fully into view
919 int spaceBelow = sel.getBottom() - bottomSelectionPixel;
920
921 // Don't scroll more than half the height of the list
922 int halfVerticalSpace = (childrenBottom - childrenTop) / 2;
923 int offset = Math.min(spaceAbove, spaceBelow);
924 offset = Math.min(offset, halfVerticalSpace);
925
926 // We placed oldSel, so offset that item
927 oldSel.offsetTopAndBottom(-offset);
928 // Now offset the selected item to get it into view
929 sel.offsetTopAndBottom(-offset);
930 }
931
932 // Fill in views above and below
933 if (!mStackFromBottom) {
934 fillUp(mSelectedPosition - 2, sel.getTop() - dividerHeight);
935 adjustViewsUpOrDown();
936 fillDown(mSelectedPosition + 1, sel.getBottom() + dividerHeight);
937 } else {
938 fillDown(mSelectedPosition + 1, sel.getBottom() + dividerHeight);
939 adjustViewsUpOrDown();
940 fillUp(mSelectedPosition - 2, sel.getTop() - dividerHeight);
941 }
942 } else if (delta < 0) {
943 /*
944 * Case 2: Scrolling up.
945 */
946
947 /*
948 * Before After
949 * | | | |
950 * +-------+ +-------+
951 * | A | | A |
952 * +-------+ => | 1 |
953 * | B | +-------+
954 * | 2 | | B |
955 * +-------+ +-------+
956 * | | | |
957 *
958 * Try to keep the top of the item about to become selected where it was.
959 * newSel = A
960 * olSel = B
961 */
962
963 if (newSel != null) {
964 // Try to position the top of newSel (A) where it was before it was selected
965 sel = makeAndAddView(selectedPosition, newSel.getTop(), true, mListPadding.left,
966 true);
967 } else {
968 // If (A) was not on screen and so did not have a view, position
969 // it above the oldSel (B)
970 sel = makeAndAddView(selectedPosition, oldSel.getTop(), false, mListPadding.left,
971 true);
972 }
973
974 // Some of the newly selected item extends above the top of the list
975 if (sel.getTop() < topSelectionPixel) {
976 // Find space required to bring the top of the selected item fully into view
977 int spaceAbove = topSelectionPixel - sel.getTop();
978
979 // Find space available below the selection into which we can scroll downwards
980 int spaceBelow = bottomSelectionPixel - sel.getBottom();
981
982 // Don't scroll more than half the height of the list
983 int halfVerticalSpace = (childrenBottom - childrenTop) / 2;
984 int offset = Math.min(spaceAbove, spaceBelow);
985 offset = Math.min(offset, halfVerticalSpace);
986
987 // Offset the selected item to get it into view
988 sel.offsetTopAndBottom(offset);
989 }
990
991 // Fill in views above and below
992 fillAboveAndBelow(sel, selectedPosition);
993 } else {
994
995 int oldTop = oldSel.getTop();
996
997 /*
998 * Case 3: Staying still
999 */
1000 sel = makeAndAddView(selectedPosition, oldTop, true, mListPadding.left, true);
1001
1002 // We're staying still...
1003 if (oldTop < childrenTop) {
1004 // ... but the top of the old selection was off screen.
1005 // (This can happen if the data changes size out from under us)
1006 int newBottom = sel.getBottom();
1007 if (newBottom < childrenTop + 20) {
1008 // Not enough visible -- bring it onscreen
1009 sel.offsetTopAndBottom(childrenTop - sel.getTop());
1010 }
1011 }
1012
1013 // Fill in views above and below
1014 fillAboveAndBelow(sel, selectedPosition);
1015 }
1016
1017 return sel;
1018 }
1019
1020 @Override
1021 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
1022 // Sets up mListPadding
1023 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
1024
1025 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
1026 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
1027 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
1028 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
1029
1030 int childWidth = 0;
1031 int childHeight = 0;
1032
1033 mItemCount = mAdapter == null ? 0 : mAdapter.getCount();
1034 if (mItemCount > 0 && (widthMode == MeasureSpec.UNSPECIFIED ||
1035 heightMode == MeasureSpec.UNSPECIFIED)) {
Romain Guy21875052010-01-06 18:48:08 -08001036 final View child = obtainView(0, mIsScrap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037
1038 measureScrapChild(child, 0, widthMeasureSpec);
1039
1040 childWidth = child.getMeasuredWidth();
1041 childHeight = child.getMeasuredHeight();
1042
1043 if (recycleOnMeasure()) {
1044 mRecycler.addScrapView(child);
1045 }
1046 }
1047
1048 if (widthMode == MeasureSpec.UNSPECIFIED) {
1049 widthSize = mListPadding.left + mListPadding.right + childWidth +
1050 getVerticalScrollbarWidth();
1051 }
1052
1053 if (heightMode == MeasureSpec.UNSPECIFIED) {
1054 heightSize = mListPadding.top + mListPadding.bottom + childHeight +
1055 getVerticalFadingEdgeLength() * 2;
1056 }
1057
1058 if (heightMode == MeasureSpec.AT_MOST) {
1059 // TODO: after first layout we should maybe start at the first visible position, not 0
1060 heightSize = measureHeightOfChildren(widthMeasureSpec, 0, NO_POSITION, heightSize, -1);
1061 }
1062
1063 setMeasuredDimension(widthSize, heightSize);
1064 mWidthMeasureSpec = widthMeasureSpec;
1065 }
1066
1067 private void measureScrapChild(View child, int position, int widthMeasureSpec) {
1068 LayoutParams p = (LayoutParams) child.getLayoutParams();
1069 if (p == null) {
Romain Guy980a9382010-01-08 15:06:28 -08001070 p = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 ViewGroup.LayoutParams.WRAP_CONTENT, 0);
The Android Open Source Project4df24232009-03-05 14:34:35 -08001072 child.setLayoutParams(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 }
1074 p.viewType = mAdapter.getItemViewType(position);
1075
1076 int childWidthSpec = ViewGroup.getChildMeasureSpec(widthMeasureSpec,
1077 mListPadding.left + mListPadding.right, p.width);
1078 int lpHeight = p.height;
1079 int childHeightSpec;
1080 if (lpHeight > 0) {
1081 childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
1082 } else {
1083 childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1084 }
1085 child.measure(childWidthSpec, childHeightSpec);
1086 }
1087
1088 /**
1089 * @return True to recycle the views used to measure this ListView in
1090 * UNSPECIFIED/AT_MOST modes, false otherwise.
1091 * @hide
1092 */
Romain Guy986003d2009-03-25 17:42:35 -07001093 @ViewDebug.ExportedProperty
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 protected boolean recycleOnMeasure() {
1095 return true;
1096 }
1097
1098 /**
1099 * Measures the height of the given range of children (inclusive) and
1100 * returns the height with this ListView's padding and divider heights
1101 * included. If maxHeight is provided, the measuring will stop when the
1102 * current height reaches maxHeight.
1103 *
1104 * @param widthMeasureSpec The width measure spec to be given to a child's
1105 * {@link View#measure(int, int)}.
1106 * @param startPosition The position of the first child to be shown.
1107 * @param endPosition The (inclusive) position of the last child to be
1108 * shown. Specify {@link #NO_POSITION} if the last child should be
1109 * the last available child from the adapter.
1110 * @param maxHeight The maximum height that will be returned (if all the
1111 * children don't fit in this value, this value will be
1112 * returned).
1113 * @param disallowPartialChildPosition In general, whether the returned
1114 * height should only contain entire children. This is more
1115 * powerful--it is the first inclusive position at which partial
1116 * children will not be allowed. Example: it looks nice to have
1117 * at least 3 completely visible children, and in portrait this
1118 * will most likely fit; but in landscape there could be times
1119 * when even 2 children can not be completely shown, so a value
1120 * of 2 (remember, inclusive) would be good (assuming
1121 * startPosition is 0).
1122 * @return The height of this ListView with the given children.
1123 */
1124 final int measureHeightOfChildren(int widthMeasureSpec, int startPosition, int endPosition,
1125 final int maxHeight, int disallowPartialChildPosition) {
1126
1127 final ListAdapter adapter = mAdapter;
1128 if (adapter == null) {
1129 return mListPadding.top + mListPadding.bottom;
1130 }
1131
1132 // Include the padding of the list
1133 int returnedHeight = mListPadding.top + mListPadding.bottom;
1134 final int dividerHeight = ((mDividerHeight > 0) && mDivider != null) ? mDividerHeight : 0;
1135 // The previous height value that was less than maxHeight and contained
1136 // no partial children
1137 int prevHeightWithoutPartialChild = 0;
1138 int i;
1139 View child;
1140
1141 // mItemCount - 1 since endPosition parameter is inclusive
1142 endPosition = (endPosition == NO_POSITION) ? adapter.getCount() - 1 : endPosition;
1143 final AbsListView.RecycleBin recycleBin = mRecycler;
1144 final boolean recyle = recycleOnMeasure();
Romain Guy21875052010-01-06 18:48:08 -08001145 final boolean[] isScrap = mIsScrap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146
1147 for (i = startPosition; i <= endPosition; ++i) {
Romain Guy21875052010-01-06 18:48:08 -08001148 child = obtainView(i, isScrap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149
1150 measureScrapChild(child, i, widthMeasureSpec);
1151
1152 if (i > 0) {
1153 // Count the divider for all but one child
1154 returnedHeight += dividerHeight;
1155 }
1156
1157 // Recycle the view before we possibly return from the method
1158 if (recyle) {
1159 recycleBin.addScrapView(child);
1160 }
1161
1162 returnedHeight += child.getMeasuredHeight();
1163
1164 if (returnedHeight >= maxHeight) {
1165 // We went over, figure out which height to return. If returnedHeight > maxHeight,
1166 // then the i'th position did not fit completely.
1167 return (disallowPartialChildPosition >= 0) // Disallowing is enabled (> -1)
1168 && (i > disallowPartialChildPosition) // We've past the min pos
1169 && (prevHeightWithoutPartialChild > 0) // We have a prev height
1170 && (returnedHeight != maxHeight) // i'th child did not fit completely
1171 ? prevHeightWithoutPartialChild
1172 : maxHeight;
1173 }
1174
1175 if ((disallowPartialChildPosition >= 0) && (i >= disallowPartialChildPosition)) {
1176 prevHeightWithoutPartialChild = returnedHeight;
1177 }
1178 }
1179
1180 // At this point, we went through the range of children, and they each
1181 // completely fit, so return the returnedHeight
1182 return returnedHeight;
1183 }
1184
1185 @Override
1186 int findMotionRow(int y) {
1187 int childCount = getChildCount();
1188 if (childCount > 0) {
1189 for (int i = 0; i < childCount; i++) {
1190 View v = getChildAt(i);
1191 if (y <= v.getBottom()) {
1192 return mFirstPosition + i;
1193 }
1194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 }
1196 return INVALID_POSITION;
1197 }
1198
1199 /**
1200 * Put a specific item at a specific location on the screen and then build
1201 * up and down from there.
1202 *
1203 * @param position The reference view to use as the starting point
1204 * @param top Pixel offset from the top of this view to the top of the
1205 * reference view.
1206 *
1207 * @return The selected view, or null if the selected view is outside the
1208 * visible area.
1209 */
1210 private View fillSpecific(int position, int top) {
1211 boolean tempIsSelected = position == mSelectedPosition;
1212 View temp = makeAndAddView(position, top, true, mListPadding.left, tempIsSelected);
1213 // Possibly changed again in fillUp if we add rows above this one.
1214 mFirstPosition = position;
1215
1216 View above;
1217 View below;
1218
1219 final int dividerHeight = mDividerHeight;
1220 if (!mStackFromBottom) {
1221 above = fillUp(position - 1, temp.getTop() - dividerHeight);
1222 // This will correct for the top of the first view not touching the top of the list
1223 adjustViewsUpOrDown();
1224 below = fillDown(position + 1, temp.getBottom() + dividerHeight);
1225 int childCount = getChildCount();
1226 if (childCount > 0) {
1227 correctTooHigh(childCount);
1228 }
1229 } else {
1230 below = fillDown(position + 1, temp.getBottom() + dividerHeight);
1231 // This will correct for the bottom of the last view not touching the bottom of the list
1232 adjustViewsUpOrDown();
1233 above = fillUp(position - 1, temp.getTop() - dividerHeight);
1234 int childCount = getChildCount();
1235 if (childCount > 0) {
1236 correctTooLow(childCount);
1237 }
1238 }
1239
1240 if (tempIsSelected) {
1241 return temp;
1242 } else if (above != null) {
1243 return above;
1244 } else {
1245 return below;
1246 }
1247 }
1248
1249 /**
1250 * Check if we have dragged the bottom of the list too high (we have pushed the
1251 * top element off the top of the screen when we did not need to). Correct by sliding
1252 * everything back down.
1253 *
1254 * @param childCount Number of children
1255 */
1256 private void correctTooHigh(int childCount) {
1257 // First see if the last item is visible. If it is not, it is OK for the
1258 // top of the list to be pushed up.
1259 int lastPosition = mFirstPosition + childCount - 1;
1260 if (lastPosition == mItemCount - 1 && childCount > 0) {
1261
1262 // Get the last child ...
1263 final View lastChild = getChildAt(childCount - 1);
1264
1265 // ... and its bottom edge
1266 final int lastBottom = lastChild.getBottom();
1267
1268 // This is bottom of our drawable area
1269 final int end = (mBottom - mTop) - mListPadding.bottom;
1270
1271 // This is how far the bottom edge of the last view is from the bottom of the
1272 // drawable area
1273 int bottomOffset = end - lastBottom;
1274 View firstChild = getChildAt(0);
1275 final int firstTop = firstChild.getTop();
1276
1277 // Make sure we are 1) Too high, and 2) Either there are more rows above the
1278 // first row or the first row is scrolled off the top of the drawable area
1279 if (bottomOffset > 0 && (mFirstPosition > 0 || firstTop < mListPadding.top)) {
1280 if (mFirstPosition == 0) {
1281 // Don't pull the top too far down
1282 bottomOffset = Math.min(bottomOffset, mListPadding.top - firstTop);
1283 }
1284 // Move everything down
1285 offsetChildrenTopAndBottom(bottomOffset);
1286 if (mFirstPosition > 0) {
1287 // Fill the gap that was opened above mFirstPosition with more rows, if
1288 // possible
1289 fillUp(mFirstPosition - 1, firstChild.getTop() - mDividerHeight);
1290 // Close up the remaining gap
1291 adjustViewsUpOrDown();
1292 }
1293
1294 }
1295 }
1296 }
1297
1298 /**
1299 * Check if we have dragged the bottom of the list too low (we have pushed the
1300 * bottom element off the bottom of the screen when we did not need to). Correct by sliding
1301 * everything back up.
1302 *
1303 * @param childCount Number of children
1304 */
1305 private void correctTooLow(int childCount) {
1306 // First see if the first item is visible. If it is not, it is OK for the
1307 // bottom of the list to be pushed down.
1308 if (mFirstPosition == 0 && childCount > 0) {
1309
1310 // Get the first child ...
1311 final View firstChild = getChildAt(0);
1312
1313 // ... and its top edge
1314 final int firstTop = firstChild.getTop();
1315
1316 // This is top of our drawable area
1317 final int start = mListPadding.top;
1318
1319 // This is bottom of our drawable area
1320 final int end = (mBottom - mTop) - mListPadding.bottom;
1321
1322 // This is how far the top edge of the first view is from the top of the
1323 // drawable area
1324 int topOffset = firstTop - start;
1325 View lastChild = getChildAt(childCount - 1);
1326 final int lastBottom = lastChild.getBottom();
1327 int lastPosition = mFirstPosition + childCount - 1;
1328
1329 // Make sure we are 1) Too low, and 2) Either there are more rows below the
1330 // last row or the last row is scrolled off the bottom of the drawable area
Romain Guy6198ae82009-08-31 17:45:55 -07001331 if (topOffset > 0) {
1332 if (lastPosition < mItemCount - 1 || lastBottom > end) {
1333 if (lastPosition == mItemCount - 1) {
1334 // Don't pull the bottom too far up
1335 topOffset = Math.min(topOffset, lastBottom - end);
1336 }
1337 // Move everything up
1338 offsetChildrenTopAndBottom(-topOffset);
1339 if (lastPosition < mItemCount - 1) {
1340 // Fill the gap that was opened below the last position with more rows, if
1341 // possible
1342 fillDown(lastPosition + 1, lastChild.getBottom() + mDividerHeight);
1343 // Close up the remaining gap
1344 adjustViewsUpOrDown();
1345 }
1346 } else if (lastPosition == mItemCount - 1) {
1347 adjustViewsUpOrDown();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 }
1349 }
1350 }
1351 }
1352
1353 @Override
1354 protected void layoutChildren() {
1355 final boolean blockLayoutRequests = mBlockLayoutRequests;
1356 if (!blockLayoutRequests) {
1357 mBlockLayoutRequests = true;
The Android Open Source Project4df24232009-03-05 14:34:35 -08001358 } else {
1359 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 }
1361
1362 try {
1363 super.layoutChildren();
1364
1365 invalidate();
1366
1367 if (mAdapter == null) {
1368 resetList();
1369 invokeOnItemScrollListener();
1370 return;
1371 }
1372
1373 int childrenTop = mListPadding.top;
1374 int childrenBottom = mBottom - mTop - mListPadding.bottom;
1375
1376 int childCount = getChildCount();
Romain Guyead0d4d2009-12-08 17:33:53 -08001377 int index = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 int delta = 0;
1379
1380 View sel;
1381 View oldSel = null;
1382 View oldFirst = null;
1383 View newSel = null;
1384
1385 View focusLayoutRestoreView = null;
1386
1387 // Remember stuff we will need down below
1388 switch (mLayoutMode) {
1389 case LAYOUT_SET_SELECTION:
1390 index = mNextSelectedPosition - mFirstPosition;
1391 if (index >= 0 && index < childCount) {
1392 newSel = getChildAt(index);
1393 }
1394 break;
1395 case LAYOUT_FORCE_TOP:
1396 case LAYOUT_FORCE_BOTTOM:
1397 case LAYOUT_SPECIFIC:
1398 case LAYOUT_SYNC:
1399 break;
1400 case LAYOUT_MOVE_SELECTION:
1401 default:
1402 // Remember the previously selected view
1403 index = mSelectedPosition - mFirstPosition;
1404 if (index >= 0 && index < childCount) {
1405 oldSel = getChildAt(index);
1406 }
1407
1408 // Remember the previous first child
1409 oldFirst = getChildAt(0);
1410
1411 if (mNextSelectedPosition >= 0) {
1412 delta = mNextSelectedPosition - mSelectedPosition;
1413 }
1414
1415 // Caution: newSel might be null
1416 newSel = getChildAt(index + delta);
1417 }
1418
1419
1420 boolean dataChanged = mDataChanged;
1421 if (dataChanged) {
1422 handleDataChanged();
1423 }
1424
1425 // Handle the empty set by removing all views that are visible
1426 // and calling it a day
1427 if (mItemCount == 0) {
1428 resetList();
1429 invokeOnItemScrollListener();
1430 return;
Romain Guyb45f1242009-03-24 21:30:00 -07001431 } else if (mItemCount != mAdapter.getCount()) {
1432 throw new IllegalStateException("The content of the adapter has changed but "
1433 + "ListView did not receive a notification. Make sure the content of "
1434 + "your adapter is not modified from a background thread, but only "
Owen Lin3940f2d2009-08-13 15:21:16 +08001435 + "from the UI thread. [in ListView(" + getId() + ", " + getClass()
1436 + ") with Adapter(" + mAdapter.getClass() + ")]");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 }
1438
1439 setSelectedPositionInt(mNextSelectedPosition);
1440
1441 // Pull all children into the RecycleBin.
1442 // These views will be reused if possible
1443 final int firstPosition = mFirstPosition;
1444 final RecycleBin recycleBin = mRecycler;
1445
1446 // reset the focus restoration
1447 View focusLayoutRestoreDirectChild = null;
1448
1449
1450 // Don't put header or footer views into the Recycler. Those are
1451 // already cached in mHeaderViews;
1452 if (dataChanged) {
1453 for (int i = 0; i < childCount; i++) {
1454 recycleBin.addScrapView(getChildAt(i));
1455 if (ViewDebug.TRACE_RECYCLER) {
1456 ViewDebug.trace(getChildAt(i),
1457 ViewDebug.RecyclerTraceType.MOVE_TO_SCRAP_HEAP, index, i);
1458 }
1459 }
1460 } else {
1461 recycleBin.fillActiveViews(childCount, firstPosition);
1462 }
1463
1464 // take focus back to us temporarily to avoid the eventual
1465 // call to clear focus when removing the focused child below
1466 // from messing things up when ViewRoot assigns focus back
1467 // to someone else
1468 final View focusedChild = getFocusedChild();
1469 if (focusedChild != null) {
1470 // TODO: in some cases focusedChild.getParent() == null
1471
1472 // we can remember the focused view to restore after relayout if the
1473 // data hasn't changed, or if the focused position is a header or footer
1474 if (!dataChanged || isDirectChildHeaderOrFooter(focusedChild)) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08001475 focusLayoutRestoreDirectChild = focusedChild;
1476 // remember the specific view that had focus
1477 focusLayoutRestoreView = findFocus();
1478 if (focusLayoutRestoreView != null) {
1479 // tell it we are going to mess with it
1480 focusLayoutRestoreView.onStartTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 }
1482 }
1483 requestFocus();
1484 }
1485
1486 // Clear out old views
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 detachAllViewsFromParent();
1488
1489 switch (mLayoutMode) {
1490 case LAYOUT_SET_SELECTION:
1491 if (newSel != null) {
1492 sel = fillFromSelection(newSel.getTop(), childrenTop, childrenBottom);
1493 } else {
1494 sel = fillFromMiddle(childrenTop, childrenBottom);
1495 }
1496 break;
1497 case LAYOUT_SYNC:
1498 sel = fillSpecific(mSyncPosition, mSpecificTop);
1499 break;
1500 case LAYOUT_FORCE_BOTTOM:
1501 sel = fillUp(mItemCount - 1, childrenBottom);
1502 adjustViewsUpOrDown();
1503 break;
1504 case LAYOUT_FORCE_TOP:
1505 mFirstPosition = 0;
1506 sel = fillFromTop(childrenTop);
1507 adjustViewsUpOrDown();
1508 break;
1509 case LAYOUT_SPECIFIC:
1510 sel = fillSpecific(reconcileSelectedPosition(), mSpecificTop);
1511 break;
1512 case LAYOUT_MOVE_SELECTION:
1513 sel = moveSelection(oldSel, newSel, delta, childrenTop, childrenBottom);
1514 break;
1515 default:
1516 if (childCount == 0) {
1517 if (!mStackFromBottom) {
1518 final int position = lookForSelectablePosition(0, true);
1519 setSelectedPositionInt(position);
1520 sel = fillFromTop(childrenTop);
1521 } else {
1522 final int position = lookForSelectablePosition(mItemCount - 1, false);
1523 setSelectedPositionInt(position);
1524 sel = fillUp(mItemCount - 1, childrenBottom);
1525 }
1526 } else {
1527 if (mSelectedPosition >= 0 && mSelectedPosition < mItemCount) {
1528 sel = fillSpecific(mSelectedPosition,
1529 oldSel == null ? childrenTop : oldSel.getTop());
1530 } else if (mFirstPosition < mItemCount) {
1531 sel = fillSpecific(mFirstPosition,
1532 oldFirst == null ? childrenTop : oldFirst.getTop());
1533 } else {
1534 sel = fillSpecific(0, childrenTop);
1535 }
1536 }
1537 break;
1538 }
1539
1540 // Flush any cached views that did not get reused above
1541 recycleBin.scrapActiveViews();
1542
1543 if (sel != null) {
Romain Guy3616a412009-09-15 13:50:37 -07001544 // the current selected item should get focus if items
1545 // are focusable
1546 if (mItemsCanFocus && hasFocus() && !sel.hasFocus()) {
1547 final boolean focusWasTaken = (sel == focusLayoutRestoreDirectChild &&
1548 focusLayoutRestoreView.requestFocus()) || sel.requestFocus();
1549 if (!focusWasTaken) {
1550 // selected item didn't take focus, fine, but still want
1551 // to make sure something else outside of the selected view
1552 // has focus
1553 final View focused = getFocusedChild();
1554 if (focused != null) {
1555 focused.clearFocus();
1556 }
1557 positionSelector(sel);
1558 } else {
1559 sel.setSelected(false);
1560 mSelectorRect.setEmpty();
1561 }
1562 } else {
1563 positionSelector(sel);
1564 }
1565 mSelectedTop = sel.getTop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 } else {
Romain Guy3616a412009-09-15 13:50:37 -07001567 if (mTouchMode > TOUCH_MODE_DOWN && mTouchMode < TOUCH_MODE_SCROLL) {
1568 View child = getChildAt(mMotionPosition - mFirstPosition);
Romain Guyb4c547a2009-09-28 13:42:20 -07001569 if (child != null) positionSelector(child);
Romain Guy3616a412009-09-15 13:50:37 -07001570 } else {
1571 mSelectedTop = 0;
1572 mSelectorRect.setEmpty();
1573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574
Romain Guy3616a412009-09-15 13:50:37 -07001575 // even if there is not selected position, we may need to restore
1576 // focus (i.e. something focusable in touch mode)
1577 if (hasFocus() && focusLayoutRestoreView != null) {
1578 focusLayoutRestoreView.requestFocus();
1579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 }
1581
1582 // tell focus view we are done mucking with it, if it is still in
1583 // our view hierarchy.
1584 if (focusLayoutRestoreView != null
1585 && focusLayoutRestoreView.getWindowToken() != null) {
1586 focusLayoutRestoreView.onFinishTemporaryDetach();
1587 }
1588
1589 mLayoutMode = LAYOUT_NORMAL;
1590 mDataChanged = false;
1591 mNeedSync = false;
1592 setNextSelectedPositionInt(mSelectedPosition);
1593
1594 updateScrollIndicators();
1595
1596 if (mItemCount > 0) {
1597 checkSelectionChanged();
1598 }
1599
1600 invokeOnItemScrollListener();
1601 } finally {
1602 if (!blockLayoutRequests) {
1603 mBlockLayoutRequests = false;
1604 }
1605 }
1606 }
1607
1608 /**
1609 * @param child a direct child of this list.
1610 * @return Whether child is a header or footer view.
1611 */
1612 private boolean isDirectChildHeaderOrFooter(View child) {
1613
1614 final ArrayList<FixedViewInfo> headers = mHeaderViewInfos;
1615 final int numHeaders = headers.size();
1616 for (int i = 0; i < numHeaders; i++) {
1617 if (child == headers.get(i).view) {
1618 return true;
1619 }
1620 }
1621 final ArrayList<FixedViewInfo> footers = mFooterViewInfos;
1622 final int numFooters = footers.size();
1623 for (int i = 0; i < numFooters; i++) {
1624 if (child == footers.get(i).view) {
1625 return true;
1626 }
1627 }
1628 return false;
1629 }
1630
1631 /**
1632 * Obtain the view and add it to our list of children. The view can be made
1633 * fresh, converted from an unused view, or used as is if it was in the
1634 * recycle bin.
1635 *
1636 * @param position Logical position in the list
1637 * @param y Top or bottom edge of the view to add
1638 * @param flow If flow is true, align top edge to y. If false, align bottom
1639 * edge to y.
1640 * @param childrenLeft Left edge where children should be positioned
1641 * @param selected Is this position selected?
1642 * @return View that was added
1643 */
1644 private View makeAndAddView(int position, int y, boolean flow, int childrenLeft,
1645 boolean selected) {
1646 View child;
1647
1648
1649 if (!mDataChanged) {
1650 // Try to use an exsiting view for this position
1651 child = mRecycler.getActiveView(position);
1652 if (child != null) {
1653 if (ViewDebug.TRACE_RECYCLER) {
1654 ViewDebug.trace(child, ViewDebug.RecyclerTraceType.RECYCLE_FROM_ACTIVE_HEAP,
1655 position, getChildCount());
1656 }
1657
1658 // Found it -- we're using an existing child
1659 // This just needs to be positioned
1660 setupChild(child, position, y, flow, childrenLeft, selected, true);
1661
1662 return child;
1663 }
1664 }
1665
1666 // Make a new view for this position, or convert an unused view if possible
Romain Guy21875052010-01-06 18:48:08 -08001667 child = obtainView(position, mIsScrap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668
1669 // This needs to be positioned and measured
Romain Guy21875052010-01-06 18:48:08 -08001670 setupChild(child, position, y, flow, childrenLeft, selected, mIsScrap[0]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671
1672 return child;
1673 }
1674
1675 /**
1676 * Add a view as a child and make sure it is measured (if necessary) and
1677 * positioned properly.
1678 *
1679 * @param child The view to add
1680 * @param position The position of this child
1681 * @param y The y position relative to which this view will be positioned
1682 * @param flowDown If true, align top edge to y. If false, align bottom
1683 * edge to y.
1684 * @param childrenLeft Left edge where children should be positioned
1685 * @param selected Is this position selected?
1686 * @param recycled Has this view been pulled from the recycle bin? If so it
1687 * does not need to be remeasured.
1688 */
1689 private void setupChild(View child, int position, int y, boolean flowDown, int childrenLeft,
1690 boolean selected, boolean recycled) {
1691 final boolean isSelected = selected && shouldShowSelector();
1692 final boolean updateChildSelected = isSelected != child.isSelected();
Romain Guy3616a412009-09-15 13:50:37 -07001693 final int mode = mTouchMode;
1694 final boolean isPressed = mode > TOUCH_MODE_DOWN && mode < TOUCH_MODE_SCROLL &&
1695 mMotionPosition == position;
1696 final boolean updateChildPressed = isPressed != child.isPressed();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 final boolean needToMeasure = !recycled || updateChildSelected || child.isLayoutRequested();
1698
1699 // Respect layout params that are already in the view. Otherwise make some up...
1700 // noinspection unchecked
1701 AbsListView.LayoutParams p = (AbsListView.LayoutParams) child.getLayoutParams();
1702 if (p == null) {
Romain Guy980a9382010-01-08 15:06:28 -08001703 p = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 ViewGroup.LayoutParams.WRAP_CONTENT, 0);
1705 }
1706 p.viewType = mAdapter.getItemViewType(position);
1707
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001708 if (recycled || (p.recycledHeaderFooter &&
1709 p.viewType == AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 attachViewToParent(child, flowDown ? -1 : 0, p);
1711 } else {
The Android Open Source Project4df24232009-03-05 14:34:35 -08001712 if (p.viewType == AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER) {
1713 p.recycledHeaderFooter = true;
1714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 addViewInLayout(child, flowDown ? -1 : 0, p, true);
1716 }
1717
1718 if (updateChildSelected) {
1719 child.setSelected(isSelected);
1720 }
1721
Romain Guy3616a412009-09-15 13:50:37 -07001722 if (updateChildPressed) {
1723 child.setPressed(isPressed);
1724 }
1725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null) {
1727 if (child instanceof Checkable) {
1728 ((Checkable) child).setChecked(mCheckStates.get(position));
1729 }
1730 }
1731
1732 if (needToMeasure) {
1733 int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
1734 mListPadding.left + mListPadding.right, p.width);
1735 int lpHeight = p.height;
1736 int childHeightSpec;
1737 if (lpHeight > 0) {
1738 childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
1739 } else {
1740 childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1741 }
1742 child.measure(childWidthSpec, childHeightSpec);
1743 } else {
1744 cleanupLayoutState(child);
1745 }
1746
1747 final int w = child.getMeasuredWidth();
1748 final int h = child.getMeasuredHeight();
1749 final int childTop = flowDown ? y : y - h;
1750
1751 if (needToMeasure) {
1752 final int childRight = childrenLeft + w;
1753 final int childBottom = childTop + h;
1754 child.layout(childrenLeft, childTop, childRight, childBottom);
1755 } else {
1756 child.offsetLeftAndRight(childrenLeft - child.getLeft());
1757 child.offsetTopAndBottom(childTop - child.getTop());
1758 }
1759
1760 if (mCachingStarted && !child.isDrawingCacheEnabled()) {
1761 child.setDrawingCacheEnabled(true);
1762 }
1763 }
1764
1765 @Override
1766 protected boolean canAnimate() {
1767 return super.canAnimate() && mItemCount > 0;
1768 }
1769
1770 /**
1771 * Sets the currently selected item. If in touch mode, the item will not be selected
1772 * but it will still be positioned appropriately. If the specified selection position
1773 * is less than 0, then the item at position 0 will be selected.
1774 *
1775 * @param position Index (starting at 0) of the data item to be selected.
1776 */
1777 @Override
1778 public void setSelection(int position) {
1779 setSelectionFromTop(position, 0);
1780 }
1781
1782 /**
1783 * Sets the selected item and positions the selection y pixels from the top edge
1784 * of the ListView. (If in touch mode, the item will not be selected but it will
1785 * still be positioned appropriately.)
1786 *
1787 * @param position Index (starting at 0) of the data item to be selected.
1788 * @param y The distance from the top edge of the ListView (plus padding) that the
1789 * item will be positioned.
1790 */
1791 public void setSelectionFromTop(int position, int y) {
1792 if (mAdapter == null) {
1793 return;
1794 }
1795
1796 if (!isInTouchMode()) {
1797 position = lookForSelectablePosition(position, true);
1798 if (position >= 0) {
1799 setNextSelectedPositionInt(position);
1800 }
1801 } else {
1802 mResurrectToPosition = position;
1803 }
1804
1805 if (position >= 0) {
1806 mLayoutMode = LAYOUT_SPECIFIC;
1807 mSpecificTop = mListPadding.top + y;
1808
1809 if (mNeedSync) {
1810 mSyncPosition = position;
1811 mSyncRowId = mAdapter.getItemId(position);
1812 }
1813
1814 requestLayout();
1815 }
1816 }
1817
1818 /**
1819 * Makes the item at the supplied position selected.
Mike Cleronf116bf82009-09-27 19:14:12 -07001820 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 * @param position the position of the item to select
1822 */
1823 @Override
1824 void setSelectionInt(int position) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 setNextSelectedPositionInt(position);
Mike Cleronf116bf82009-09-27 19:14:12 -07001826 boolean awakeScrollbars = false;
1827
1828 final int selectedPosition = mSelectedPosition;
1829
1830 if (selectedPosition >= 0) {
1831 if (position == selectedPosition - 1) {
1832 awakeScrollbars = true;
1833 } else if (position == selectedPosition + 1) {
1834 awakeScrollbars = true;
1835 }
1836 }
1837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 layoutChildren();
Mike Cleronf116bf82009-09-27 19:14:12 -07001839
1840 if (awakeScrollbars) {
1841 awakenScrollBars();
1842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 }
1844
1845 /**
1846 * Find a position that can be selected (i.e., is not a separator).
1847 *
1848 * @param position The starting position to look at.
1849 * @param lookDown Whether to look down for other positions.
1850 * @return The next selectable position starting at position and then searching either up or
1851 * down. Returns {@link #INVALID_POSITION} if nothing can be found.
1852 */
1853 @Override
1854 int lookForSelectablePosition(int position, boolean lookDown) {
1855 final ListAdapter adapter = mAdapter;
1856 if (adapter == null || isInTouchMode()) {
1857 return INVALID_POSITION;
1858 }
1859
1860 final int count = adapter.getCount();
1861 if (!mAreAllItemsSelectable) {
1862 if (lookDown) {
1863 position = Math.max(0, position);
1864 while (position < count && !adapter.isEnabled(position)) {
1865 position++;
1866 }
1867 } else {
1868 position = Math.min(position, count - 1);
1869 while (position >= 0 && !adapter.isEnabled(position)) {
1870 position--;
1871 }
1872 }
1873
1874 if (position < 0 || position >= count) {
1875 return INVALID_POSITION;
1876 }
1877 return position;
1878 } else {
1879 if (position < 0 || position >= count) {
1880 return INVALID_POSITION;
1881 }
1882 return position;
1883 }
1884 }
1885
svetoslavganov75986cf2009-05-14 22:28:01 -07001886 @Override
1887 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
1888 boolean populated = super.dispatchPopulateAccessibilityEvent(event);
1889
Amith Yamasanid296faf2009-06-04 12:11:25 -07001890 // If the item count is less than 15 then subtract disabled items from the count and
1891 // position. Otherwise ignore disabled items.
svetoslavganov75986cf2009-05-14 22:28:01 -07001892 if (!populated) {
1893 int itemCount = 0;
1894 int currentItemIndex = getSelectedItemPosition();
1895
1896 ListAdapter adapter = getAdapter();
1897 if (adapter != null) {
Amith Yamasanid296faf2009-06-04 12:11:25 -07001898 final int count = adapter.getCount();
1899 if (count < 15) {
1900 for (int i = 0; i < count; i++) {
1901 if (adapter.isEnabled(i)) {
1902 itemCount++;
1903 } else if (i <= currentItemIndex) {
1904 currentItemIndex--;
1905 }
svetoslavganov75986cf2009-05-14 22:28:01 -07001906 }
Amith Yamasanid296faf2009-06-04 12:11:25 -07001907 } else {
1908 itemCount = count;
svetoslavganov75986cf2009-05-14 22:28:01 -07001909 }
1910 }
1911
1912 event.setItemCount(itemCount);
1913 event.setCurrentItemIndex(currentItemIndex);
1914 }
1915
1916 return populated;
1917 }
1918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 /**
1920 * setSelectionAfterHeaderView set the selection to be the first list item
1921 * after the header views.
1922 */
1923 public void setSelectionAfterHeaderView() {
1924 final int count = mHeaderViewInfos.size();
1925 if (count > 0) {
1926 mNextSelectedPosition = 0;
1927 return;
1928 }
1929
1930 if (mAdapter != null) {
1931 setSelection(count);
1932 } else {
1933 mNextSelectedPosition = count;
1934 mLayoutMode = LAYOUT_SET_SELECTION;
1935 }
1936
1937 }
1938
1939 @Override
1940 public boolean dispatchKeyEvent(KeyEvent event) {
1941 // Dispatch in the normal way
1942 boolean handled = super.dispatchKeyEvent(event);
1943 if (!handled) {
1944 // If we didn't handle it...
1945 View focused = getFocusedChild();
1946 if (focused != null && event.getAction() == KeyEvent.ACTION_DOWN) {
1947 // ... and our focused child didn't handle it
1948 // ... give it to ourselves so we can scroll if necessary
1949 handled = onKeyDown(event.getKeyCode(), event);
1950 }
1951 }
1952 return handled;
1953 }
1954
1955 @Override
1956 public boolean onKeyDown(int keyCode, KeyEvent event) {
1957 return commonKey(keyCode, 1, event);
1958 }
1959
1960 @Override
1961 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
1962 return commonKey(keyCode, repeatCount, event);
1963 }
1964
1965 @Override
1966 public boolean onKeyUp(int keyCode, KeyEvent event) {
1967 return commonKey(keyCode, 1, event);
1968 }
1969
1970 private boolean commonKey(int keyCode, int count, KeyEvent event) {
1971 if (mAdapter == null) {
1972 return false;
1973 }
1974
1975 if (mDataChanged) {
1976 layoutChildren();
1977 }
1978
1979 boolean handled = false;
1980 int action = event.getAction();
1981
1982 if (action != KeyEvent.ACTION_UP) {
1983 if (mSelectedPosition < 0) {
1984 switch (keyCode) {
1985 case KeyEvent.KEYCODE_DPAD_UP:
1986 case KeyEvent.KEYCODE_DPAD_DOWN:
1987 case KeyEvent.KEYCODE_DPAD_CENTER:
1988 case KeyEvent.KEYCODE_ENTER:
1989 case KeyEvent.KEYCODE_SPACE:
1990 if (resurrectSelection()) {
1991 return true;
1992 }
1993 }
1994 }
1995 switch (keyCode) {
1996 case KeyEvent.KEYCODE_DPAD_UP:
1997 if (!event.isAltPressed()) {
1998 while (count > 0) {
1999 handled = arrowScroll(FOCUS_UP);
2000 count--;
2001 }
2002 } else {
2003 handled = fullScroll(FOCUS_UP);
2004 }
2005 break;
2006
2007 case KeyEvent.KEYCODE_DPAD_DOWN:
2008 if (!event.isAltPressed()) {
2009 while (count > 0) {
2010 handled = arrowScroll(FOCUS_DOWN);
2011 count--;
2012 }
2013 } else {
2014 handled = fullScroll(FOCUS_DOWN);
2015 }
2016 break;
2017
2018 case KeyEvent.KEYCODE_DPAD_LEFT:
2019 handled = handleHorizontalFocusWithinListItem(View.FOCUS_LEFT);
2020 break;
2021 case KeyEvent.KEYCODE_DPAD_RIGHT:
2022 handled = handleHorizontalFocusWithinListItem(View.FOCUS_RIGHT);
2023 break;
2024
2025 case KeyEvent.KEYCODE_DPAD_CENTER:
2026 case KeyEvent.KEYCODE_ENTER:
2027 if (mItemCount > 0 && event.getRepeatCount() == 0) {
2028 keyPressed();
2029 }
2030 handled = true;
2031 break;
2032
2033 case KeyEvent.KEYCODE_SPACE:
2034 if (mPopup == null || !mPopup.isShowing()) {
2035 if (!event.isShiftPressed()) {
2036 pageScroll(FOCUS_DOWN);
2037 } else {
2038 pageScroll(FOCUS_UP);
2039 }
2040 handled = true;
2041 }
2042 break;
2043 }
2044 }
2045
2046 if (!handled) {
2047 handled = sendToTextFilter(keyCode, count, event);
2048 }
2049
2050 if (handled) {
2051 return true;
2052 } else {
2053 switch (action) {
2054 case KeyEvent.ACTION_DOWN:
2055 return super.onKeyDown(keyCode, event);
2056
2057 case KeyEvent.ACTION_UP:
2058 return super.onKeyUp(keyCode, event);
2059
2060 case KeyEvent.ACTION_MULTIPLE:
2061 return super.onKeyMultiple(keyCode, count, event);
2062
2063 default: // shouldn't happen
2064 return false;
2065 }
2066 }
2067 }
2068
2069 /**
2070 * Scrolls up or down by the number of items currently present on screen.
2071 *
2072 * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
2073 * @return whether selection was moved
2074 */
2075 boolean pageScroll(int direction) {
2076 int nextPage = -1;
2077 boolean down = false;
2078
2079 if (direction == FOCUS_UP) {
2080 nextPage = Math.max(0, mSelectedPosition - getChildCount() - 1);
2081 } else if (direction == FOCUS_DOWN) {
2082 nextPage = Math.min(mItemCount - 1, mSelectedPosition + getChildCount() - 1);
2083 down = true;
2084 }
2085
2086 if (nextPage >= 0) {
2087 int position = lookForSelectablePosition(nextPage, down);
2088 if (position >= 0) {
2089 mLayoutMode = LAYOUT_SPECIFIC;
2090 mSpecificTop = mPaddingTop + getVerticalFadingEdgeLength();
2091
2092 if (down && position > mItemCount - getChildCount()) {
2093 mLayoutMode = LAYOUT_FORCE_BOTTOM;
2094 }
2095
2096 if (!down && position < getChildCount()) {
2097 mLayoutMode = LAYOUT_FORCE_TOP;
2098 }
2099
2100 setSelectionInt(position);
2101 invokeOnItemScrollListener();
Mike Cleronf116bf82009-09-27 19:14:12 -07002102 if (!awakenScrollBars()) {
2103 invalidate();
2104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105
2106 return true;
2107 }
2108 }
2109
2110 return false;
2111 }
2112
2113 /**
2114 * Go to the last or first item if possible (not worrying about panning across or navigating
2115 * within the internal focus of the currently selected item.)
2116 *
2117 * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
2118 *
2119 * @return whether selection was moved
2120 */
2121 boolean fullScroll(int direction) {
2122 boolean moved = false;
2123 if (direction == FOCUS_UP) {
2124 if (mSelectedPosition != 0) {
2125 int position = lookForSelectablePosition(0, true);
2126 if (position >= 0) {
2127 mLayoutMode = LAYOUT_FORCE_TOP;
2128 setSelectionInt(position);
2129 invokeOnItemScrollListener();
2130 }
2131 moved = true;
2132 }
2133 } else if (direction == FOCUS_DOWN) {
2134 if (mSelectedPosition < mItemCount - 1) {
2135 int position = lookForSelectablePosition(mItemCount - 1, true);
2136 if (position >= 0) {
2137 mLayoutMode = LAYOUT_FORCE_BOTTOM;
2138 setSelectionInt(position);
2139 invokeOnItemScrollListener();
2140 }
2141 moved = true;
2142 }
2143 }
2144
Mike Cleronf116bf82009-09-27 19:14:12 -07002145 if (moved && !awakenScrollBars()) {
2146 awakenScrollBars();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 invalidate();
2148 }
2149
2150 return moved;
2151 }
2152
2153 /**
2154 * To avoid horizontal focus searches changing the selected item, we
2155 * manually focus search within the selected item (as applicable), and
2156 * prevent focus from jumping to something within another item.
2157 * @param direction one of {View.FOCUS_LEFT, View.FOCUS_RIGHT}
2158 * @return Whether this consumes the key event.
2159 */
2160 private boolean handleHorizontalFocusWithinListItem(int direction) {
2161 if (direction != View.FOCUS_LEFT && direction != View.FOCUS_RIGHT) {
Romain Guy304eefa2009-03-24 20:01:49 -07002162 throw new IllegalArgumentException("direction must be one of"
2163 + " {View.FOCUS_LEFT, View.FOCUS_RIGHT}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 }
2165
2166 final int numChildren = getChildCount();
2167 if (mItemsCanFocus && numChildren > 0 && mSelectedPosition != INVALID_POSITION) {
2168 final View selectedView = getSelectedView();
Romain Guy304eefa2009-03-24 20:01:49 -07002169 if (selectedView != null && selectedView.hasFocus() &&
2170 selectedView instanceof ViewGroup) {
2171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002172 final View currentFocus = selectedView.findFocus();
2173 final View nextFocus = FocusFinder.getInstance().findNextFocus(
Romain Guy304eefa2009-03-24 20:01:49 -07002174 (ViewGroup) selectedView, currentFocus, direction);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 if (nextFocus != null) {
2176 // do the math to get interesting rect in next focus' coordinates
2177 currentFocus.getFocusedRect(mTempRect);
2178 offsetDescendantRectToMyCoords(currentFocus, mTempRect);
2179 offsetRectIntoDescendantCoords(nextFocus, mTempRect);
2180 if (nextFocus.requestFocus(direction, mTempRect)) {
2181 return true;
2182 }
2183 }
2184 // we are blocking the key from being handled (by returning true)
2185 // if the global result is going to be some other view within this
2186 // list. this is to acheive the overall goal of having
2187 // horizontal d-pad navigation remain in the current item.
Romain Guy304eefa2009-03-24 20:01:49 -07002188 final View globalNextFocus = FocusFinder.getInstance().findNextFocus(
2189 (ViewGroup) getRootView(), currentFocus, direction);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 if (globalNextFocus != null) {
2191 return isViewAncestorOf(globalNextFocus, this);
2192 }
2193 }
2194 }
2195 return false;
2196 }
2197
2198 /**
2199 * Scrolls to the next or previous item if possible.
2200 *
2201 * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
2202 *
2203 * @return whether selection was moved
2204 */
2205 boolean arrowScroll(int direction) {
2206 try {
2207 mInLayout = true;
2208 final boolean handled = arrowScrollImpl(direction);
2209 if (handled) {
2210 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2211 }
2212 return handled;
2213 } finally {
2214 mInLayout = false;
2215 }
2216 }
2217
2218 /**
2219 * Handle an arrow scroll going up or down. Take into account whether items are selectable,
2220 * whether there are focusable items etc.
2221 *
2222 * @param direction Either {@link android.view.View#FOCUS_UP} or {@link android.view.View#FOCUS_DOWN}.
2223 * @return Whether any scrolling, selection or focus change occured.
2224 */
2225 private boolean arrowScrollImpl(int direction) {
2226 if (getChildCount() <= 0) {
2227 return false;
2228 }
2229
2230 View selectedView = getSelectedView();
2231
2232 int nextSelectedPosition = lookForSelectablePositionOnScreen(direction);
2233 int amountToScroll = amountToScroll(direction, nextSelectedPosition);
2234
2235 // if we are moving focus, we may OVERRIDE the default behavior
2236 final ArrowScrollFocusResult focusResult = mItemsCanFocus ? arrowScrollFocused(direction) : null;
2237 if (focusResult != null) {
2238 nextSelectedPosition = focusResult.getSelectedPosition();
2239 amountToScroll = focusResult.getAmountToScroll();
2240 }
2241
2242 boolean needToRedraw = focusResult != null;
2243 if (nextSelectedPosition != INVALID_POSITION) {
2244 handleNewSelectionChange(selectedView, direction, nextSelectedPosition, focusResult != null);
2245 setSelectedPositionInt(nextSelectedPosition);
2246 setNextSelectedPositionInt(nextSelectedPosition);
2247 selectedView = getSelectedView();
2248 if (mItemsCanFocus && focusResult == null) {
2249 // there was no new view found to take focus, make sure we
2250 // don't leave focus with the old selection
2251 final View focused = getFocusedChild();
2252 if (focused != null) {
2253 focused.clearFocus();
2254 }
2255 }
2256 needToRedraw = true;
2257 checkSelectionChanged();
2258 }
2259
2260 if (amountToScroll > 0) {
2261 scrollListItemsBy((direction == View.FOCUS_UP) ? amountToScroll : -amountToScroll);
2262 needToRedraw = true;
2263 }
2264
2265 // if we didn't find a new focusable, make sure any existing focused
2266 // item that was panned off screen gives up focus.
2267 if (mItemsCanFocus && (focusResult == null)
2268 && selectedView != null && selectedView.hasFocus()) {
2269 final View focused = selectedView.findFocus();
2270 if (distanceToView(focused) > 0) {
2271 focused.clearFocus();
2272 }
2273 }
2274
2275 // if the current selection is panned off, we need to remove the selection
2276 if (nextSelectedPosition == INVALID_POSITION && selectedView != null
2277 && !isViewAncestorOf(selectedView, this)) {
2278 selectedView = null;
2279 hideSelector();
2280
2281 // but we don't want to set the ressurect position (that would make subsequent
2282 // unhandled key events bring back the item we just scrolled off!)
2283 mResurrectToPosition = INVALID_POSITION;
2284 }
2285
2286 if (needToRedraw) {
2287 if (selectedView != null) {
2288 positionSelector(selectedView);
2289 mSelectedTop = selectedView.getTop();
2290 }
Mike Cleronf116bf82009-09-27 19:14:12 -07002291 if (!awakenScrollBars()) {
2292 invalidate();
2293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 invokeOnItemScrollListener();
2295 return true;
2296 }
2297
2298 return false;
2299 }
2300
2301 /**
2302 * When selection changes, it is possible that the previously selected or the
2303 * next selected item will change its size. If so, we need to offset some folks,
2304 * and re-layout the items as appropriate.
2305 *
2306 * @param selectedView The currently selected view (before changing selection).
2307 * should be <code>null</code> if there was no previous selection.
2308 * @param direction Either {@link android.view.View#FOCUS_UP} or
2309 * {@link android.view.View#FOCUS_DOWN}.
2310 * @param newSelectedPosition The position of the next selection.
2311 * @param newFocusAssigned whether new focus was assigned. This matters because
2312 * when something has focus, we don't want to show selection (ugh).
2313 */
2314 private void handleNewSelectionChange(View selectedView, int direction, int newSelectedPosition,
2315 boolean newFocusAssigned) {
2316 if (newSelectedPosition == INVALID_POSITION) {
2317 throw new IllegalArgumentException("newSelectedPosition needs to be valid");
2318 }
2319
2320 // whether or not we are moving down or up, we want to preserve the
2321 // top of whatever view is on top:
2322 // - moving down: the view that had selection
2323 // - moving up: the view that is getting selection
2324 View topView;
2325 View bottomView;
2326 int topViewIndex, bottomViewIndex;
2327 boolean topSelected = false;
2328 final int selectedIndex = mSelectedPosition - mFirstPosition;
2329 final int nextSelectedIndex = newSelectedPosition - mFirstPosition;
2330 if (direction == View.FOCUS_UP) {
2331 topViewIndex = nextSelectedIndex;
2332 bottomViewIndex = selectedIndex;
2333 topView = getChildAt(topViewIndex);
2334 bottomView = selectedView;
2335 topSelected = true;
2336 } else {
2337 topViewIndex = selectedIndex;
2338 bottomViewIndex = nextSelectedIndex;
2339 topView = selectedView;
2340 bottomView = getChildAt(bottomViewIndex);
2341 }
2342
2343 final int numChildren = getChildCount();
2344
2345 // start with top view: is it changing size?
2346 if (topView != null) {
2347 topView.setSelected(!newFocusAssigned && topSelected);
2348 measureAndAdjustDown(topView, topViewIndex, numChildren);
2349 }
2350
2351 // is the bottom view changing size?
2352 if (bottomView != null) {
2353 bottomView.setSelected(!newFocusAssigned && !topSelected);
2354 measureAndAdjustDown(bottomView, bottomViewIndex, numChildren);
2355 }
2356 }
2357
2358 /**
2359 * Re-measure a child, and if its height changes, lay it out preserving its
2360 * top, and adjust the children below it appropriately.
2361 * @param child The child
2362 * @param childIndex The view group index of the child.
2363 * @param numChildren The number of children in the view group.
2364 */
2365 private void measureAndAdjustDown(View child, int childIndex, int numChildren) {
2366 int oldHeight = child.getHeight();
2367 measureItem(child);
2368 if (child.getMeasuredHeight() != oldHeight) {
2369 // lay out the view, preserving its top
2370 relayoutMeasuredItem(child);
2371
2372 // adjust views below appropriately
2373 final int heightDelta = child.getMeasuredHeight() - oldHeight;
2374 for (int i = childIndex + 1; i < numChildren; i++) {
2375 getChildAt(i).offsetTopAndBottom(heightDelta);
2376 }
2377 }
2378 }
2379
2380 /**
2381 * Measure a particular list child.
2382 * TODO: unify with setUpChild.
2383 * @param child The child.
2384 */
2385 private void measureItem(View child) {
2386 ViewGroup.LayoutParams p = child.getLayoutParams();
2387 if (p == null) {
2388 p = new ViewGroup.LayoutParams(
Romain Guy980a9382010-01-08 15:06:28 -08002389 ViewGroup.LayoutParams.MATCH_PARENT,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 ViewGroup.LayoutParams.WRAP_CONTENT);
2391 }
2392
2393 int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
2394 mListPadding.left + mListPadding.right, p.width);
2395 int lpHeight = p.height;
2396 int childHeightSpec;
2397 if (lpHeight > 0) {
2398 childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
2399 } else {
2400 childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
2401 }
2402 child.measure(childWidthSpec, childHeightSpec);
2403 }
2404
2405 /**
2406 * Layout a child that has been measured, preserving its top position.
2407 * TODO: unify with setUpChild.
2408 * @param child The child.
2409 */
2410 private void relayoutMeasuredItem(View child) {
2411 final int w = child.getMeasuredWidth();
2412 final int h = child.getMeasuredHeight();
2413 final int childLeft = mListPadding.left;
2414 final int childRight = childLeft + w;
2415 final int childTop = child.getTop();
2416 final int childBottom = childTop + h;
2417 child.layout(childLeft, childTop, childRight, childBottom);
2418 }
2419
2420 /**
2421 * @return The amount to preview next items when arrow srolling.
2422 */
2423 private int getArrowScrollPreviewLength() {
2424 return Math.max(MIN_SCROLL_PREVIEW_PIXELS, getVerticalFadingEdgeLength());
2425 }
2426
2427 /**
2428 * Determine how much we need to scroll in order to get the next selected view
2429 * visible, with a fading edge showing below as applicable. The amount is
2430 * capped at {@link #getMaxScrollAmount()} .
2431 *
2432 * @param direction either {@link android.view.View#FOCUS_UP} or
2433 * {@link android.view.View#FOCUS_DOWN}.
2434 * @param nextSelectedPosition The position of the next selection, or
2435 * {@link #INVALID_POSITION} if there is no next selectable position
2436 * @return The amount to scroll. Note: this is always positive! Direction
2437 * needs to be taken into account when actually scrolling.
2438 */
2439 private int amountToScroll(int direction, int nextSelectedPosition) {
2440 final int listBottom = getHeight() - mListPadding.bottom;
2441 final int listTop = mListPadding.top;
2442
2443 final int numChildren = getChildCount();
2444
2445 if (direction == View.FOCUS_DOWN) {
2446 int indexToMakeVisible = numChildren - 1;
2447 if (nextSelectedPosition != INVALID_POSITION) {
2448 indexToMakeVisible = nextSelectedPosition - mFirstPosition;
2449 }
2450
2451 final int positionToMakeVisible = mFirstPosition + indexToMakeVisible;
2452 final View viewToMakeVisible = getChildAt(indexToMakeVisible);
2453
2454 int goalBottom = listBottom;
2455 if (positionToMakeVisible < mItemCount - 1) {
2456 goalBottom -= getArrowScrollPreviewLength();
2457 }
2458
2459 if (viewToMakeVisible.getBottom() <= goalBottom) {
2460 // item is fully visible.
2461 return 0;
2462 }
2463
2464 if (nextSelectedPosition != INVALID_POSITION
2465 && (goalBottom - viewToMakeVisible.getTop()) >= getMaxScrollAmount()) {
2466 // item already has enough of it visible, changing selection is good enough
2467 return 0;
2468 }
2469
2470 int amountToScroll = (viewToMakeVisible.getBottom() - goalBottom);
2471
2472 if ((mFirstPosition + numChildren) == mItemCount) {
2473 // last is last in list -> make sure we don't scroll past it
2474 final int max = getChildAt(numChildren - 1).getBottom() - listBottom;
2475 amountToScroll = Math.min(amountToScroll, max);
2476 }
2477
2478 return Math.min(amountToScroll, getMaxScrollAmount());
2479 } else {
2480 int indexToMakeVisible = 0;
2481 if (nextSelectedPosition != INVALID_POSITION) {
2482 indexToMakeVisible = nextSelectedPosition - mFirstPosition;
2483 }
2484 final int positionToMakeVisible = mFirstPosition + indexToMakeVisible;
2485 final View viewToMakeVisible = getChildAt(indexToMakeVisible);
2486 int goalTop = listTop;
2487 if (positionToMakeVisible > 0) {
2488 goalTop += getArrowScrollPreviewLength();
2489 }
2490 if (viewToMakeVisible.getTop() >= goalTop) {
2491 // item is fully visible.
2492 return 0;
2493 }
2494
2495 if (nextSelectedPosition != INVALID_POSITION &&
2496 (viewToMakeVisible.getBottom() - goalTop) >= getMaxScrollAmount()) {
2497 // item already has enough of it visible, changing selection is good enough
2498 return 0;
2499 }
2500
2501 int amountToScroll = (goalTop - viewToMakeVisible.getTop());
2502 if (mFirstPosition == 0) {
2503 // first is first in list -> make sure we don't scroll past it
2504 final int max = listTop - getChildAt(0).getTop();
2505 amountToScroll = Math.min(amountToScroll, max);
2506 }
2507 return Math.min(amountToScroll, getMaxScrollAmount());
2508 }
2509 }
2510
2511 /**
2512 * Holds results of focus aware arrow scrolling.
2513 */
2514 static private class ArrowScrollFocusResult {
2515 private int mSelectedPosition;
2516 private int mAmountToScroll;
2517
2518 /**
2519 * How {@link android.widget.ListView#arrowScrollFocused} returns its values.
2520 */
2521 void populate(int selectedPosition, int amountToScroll) {
2522 mSelectedPosition = selectedPosition;
2523 mAmountToScroll = amountToScroll;
2524 }
2525
2526 public int getSelectedPosition() {
2527 return mSelectedPosition;
2528 }
2529
2530 public int getAmountToScroll() {
2531 return mAmountToScroll;
2532 }
2533 }
2534
2535 /**
2536 * @param direction either {@link android.view.View#FOCUS_UP} or
2537 * {@link android.view.View#FOCUS_DOWN}.
2538 * @return The position of the next selectable position of the views that
2539 * are currently visible, taking into account the fact that there might
2540 * be no selection. Returns {@link #INVALID_POSITION} if there is no
2541 * selectable view on screen in the given direction.
2542 */
2543 private int lookForSelectablePositionOnScreen(int direction) {
2544 final int firstPosition = mFirstPosition;
2545 if (direction == View.FOCUS_DOWN) {
2546 int startPos = (mSelectedPosition != INVALID_POSITION) ?
2547 mSelectedPosition + 1 :
2548 firstPosition;
2549 if (startPos >= mAdapter.getCount()) {
2550 return INVALID_POSITION;
2551 }
2552 if (startPos < firstPosition) {
2553 startPos = firstPosition;
2554 }
2555
2556 final int lastVisiblePos = getLastVisiblePosition();
2557 final ListAdapter adapter = getAdapter();
2558 for (int pos = startPos; pos <= lastVisiblePos; pos++) {
2559 if (adapter.isEnabled(pos)
2560 && getChildAt(pos - firstPosition).getVisibility() == View.VISIBLE) {
2561 return pos;
2562 }
2563 }
2564 } else {
2565 int last = firstPosition + getChildCount() - 1;
2566 int startPos = (mSelectedPosition != INVALID_POSITION) ?
2567 mSelectedPosition - 1 :
2568 firstPosition + getChildCount() - 1;
2569 if (startPos < 0) {
2570 return INVALID_POSITION;
2571 }
2572 if (startPos > last) {
2573 startPos = last;
2574 }
2575
2576 final ListAdapter adapter = getAdapter();
2577 for (int pos = startPos; pos >= firstPosition; pos--) {
2578 if (adapter.isEnabled(pos)
2579 && getChildAt(pos - firstPosition).getVisibility() == View.VISIBLE) {
2580 return pos;
2581 }
2582 }
2583 }
2584 return INVALID_POSITION;
2585 }
2586
2587 /**
2588 * Do an arrow scroll based on focus searching. If a new view is
2589 * given focus, return the selection delta and amount to scroll via
2590 * an {@link ArrowScrollFocusResult}, otherwise, return null.
2591 *
2592 * @param direction either {@link android.view.View#FOCUS_UP} or
2593 * {@link android.view.View#FOCUS_DOWN}.
2594 * @return The result if focus has changed, or <code>null</code>.
2595 */
2596 private ArrowScrollFocusResult arrowScrollFocused(final int direction) {
2597 final View selectedView = getSelectedView();
2598 View newFocus;
2599 if (selectedView != null && selectedView.hasFocus()) {
2600 View oldFocus = selectedView.findFocus();
2601 newFocus = FocusFinder.getInstance().findNextFocus(this, oldFocus, direction);
2602 } else {
2603 if (direction == View.FOCUS_DOWN) {
2604 final boolean topFadingEdgeShowing = (mFirstPosition > 0);
2605 final int listTop = mListPadding.top +
2606 (topFadingEdgeShowing ? getArrowScrollPreviewLength() : 0);
2607 final int ySearchPoint =
2608 (selectedView != null && selectedView.getTop() > listTop) ?
2609 selectedView.getTop() :
2610 listTop;
2611 mTempRect.set(0, ySearchPoint, 0, ySearchPoint);
2612 } else {
2613 final boolean bottomFadingEdgeShowing =
2614 (mFirstPosition + getChildCount() - 1) < mItemCount;
2615 final int listBottom = getHeight() - mListPadding.bottom -
2616 (bottomFadingEdgeShowing ? getArrowScrollPreviewLength() : 0);
2617 final int ySearchPoint =
2618 (selectedView != null && selectedView.getBottom() < listBottom) ?
2619 selectedView.getBottom() :
2620 listBottom;
2621 mTempRect.set(0, ySearchPoint, 0, ySearchPoint);
2622 }
2623 newFocus = FocusFinder.getInstance().findNextFocusFromRect(this, mTempRect, direction);
2624 }
2625
2626 if (newFocus != null) {
2627 final int positionOfNewFocus = positionOfNewFocus(newFocus);
2628
2629 // if the focus change is in a different new position, make sure
2630 // we aren't jumping over another selectable position
2631 if (mSelectedPosition != INVALID_POSITION && positionOfNewFocus != mSelectedPosition) {
2632 final int selectablePosition = lookForSelectablePositionOnScreen(direction);
2633 if (selectablePosition != INVALID_POSITION &&
2634 ((direction == View.FOCUS_DOWN && selectablePosition < positionOfNewFocus) ||
2635 (direction == View.FOCUS_UP && selectablePosition > positionOfNewFocus))) {
2636 return null;
2637 }
2638 }
2639
2640 int focusScroll = amountToScrollToNewFocus(direction, newFocus, positionOfNewFocus);
2641
2642 final int maxScrollAmount = getMaxScrollAmount();
2643 if (focusScroll < maxScrollAmount) {
2644 // not moving too far, safe to give next view focus
2645 newFocus.requestFocus(direction);
2646 mArrowScrollFocusResult.populate(positionOfNewFocus, focusScroll);
2647 return mArrowScrollFocusResult;
2648 } else if (distanceToView(newFocus) < maxScrollAmount){
2649 // Case to consider:
2650 // too far to get entire next focusable on screen, but by going
2651 // max scroll amount, we are getting it at least partially in view,
2652 // so give it focus and scroll the max ammount.
2653 newFocus.requestFocus(direction);
2654 mArrowScrollFocusResult.populate(positionOfNewFocus, maxScrollAmount);
2655 return mArrowScrollFocusResult;
2656 }
2657 }
2658 return null;
2659 }
2660
2661 /**
2662 * @param newFocus The view that would have focus.
2663 * @return the position that contains newFocus
2664 */
2665 private int positionOfNewFocus(View newFocus) {
2666 final int numChildren = getChildCount();
2667 for (int i = 0; i < numChildren; i++) {
2668 final View child = getChildAt(i);
2669 if (isViewAncestorOf(newFocus, child)) {
2670 return mFirstPosition + i;
2671 }
2672 }
2673 throw new IllegalArgumentException("newFocus is not a child of any of the"
2674 + " children of the list!");
2675 }
2676
2677 /**
2678 * Return true if child is an ancestor of parent, (or equal to the parent).
2679 */
2680 private boolean isViewAncestorOf(View child, View parent) {
2681 if (child == parent) {
2682 return true;
2683 }
2684
2685 final ViewParent theParent = child.getParent();
2686 return (theParent instanceof ViewGroup) && isViewAncestorOf((View) theParent, parent);
2687 }
2688
2689 /**
2690 * Determine how much we need to scroll in order to get newFocus in view.
2691 * @param direction either {@link android.view.View#FOCUS_UP} or
2692 * {@link android.view.View#FOCUS_DOWN}.
2693 * @param newFocus The view that would take focus.
2694 * @param positionOfNewFocus The position of the list item containing newFocus
2695 * @return The amount to scroll. Note: this is always positive! Direction
2696 * needs to be taken into account when actually scrolling.
2697 */
2698 private int amountToScrollToNewFocus(int direction, View newFocus, int positionOfNewFocus) {
2699 int amountToScroll = 0;
2700 newFocus.getDrawingRect(mTempRect);
2701 offsetDescendantRectToMyCoords(newFocus, mTempRect);
2702 if (direction == View.FOCUS_UP) {
2703 if (mTempRect.top < mListPadding.top) {
2704 amountToScroll = mListPadding.top - mTempRect.top;
2705 if (positionOfNewFocus > 0) {
2706 amountToScroll += getArrowScrollPreviewLength();
2707 }
2708 }
2709 } else {
2710 final int listBottom = getHeight() - mListPadding.bottom;
2711 if (mTempRect.bottom > listBottom) {
2712 amountToScroll = mTempRect.bottom - listBottom;
2713 if (positionOfNewFocus < mItemCount - 1) {
2714 amountToScroll += getArrowScrollPreviewLength();
2715 }
2716 }
2717 }
2718 return amountToScroll;
2719 }
2720
2721 /**
2722 * Determine the distance to the nearest edge of a view in a particular
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -08002723 * direction.
2724 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 * @param descendant A descendant of this list.
2726 * @return The distance, or 0 if the nearest edge is already on screen.
2727 */
2728 private int distanceToView(View descendant) {
2729 int distance = 0;
2730 descendant.getDrawingRect(mTempRect);
2731 offsetDescendantRectToMyCoords(descendant, mTempRect);
2732 final int listBottom = mBottom - mTop - mListPadding.bottom;
2733 if (mTempRect.bottom < mListPadding.top) {
2734 distance = mListPadding.top - mTempRect.bottom;
2735 } else if (mTempRect.top > listBottom) {
2736 distance = mTempRect.top - listBottom;
2737 }
2738 return distance;
2739 }
2740
2741
2742 /**
2743 * Scroll the children by amount, adding a view at the end and removing
2744 * views that fall off as necessary.
2745 *
2746 * @param amount The amount (positive or negative) to scroll.
2747 */
2748 private void scrollListItemsBy(int amount) {
2749 offsetChildrenTopAndBottom(amount);
2750
2751 final int listBottom = getHeight() - mListPadding.bottom;
2752 final int listTop = mListPadding.top;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002753 final AbsListView.RecycleBin recycleBin = mRecycler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754
2755 if (amount < 0) {
2756 // shifted items up
2757
2758 // may need to pan views into the bottom space
2759 int numChildren = getChildCount();
2760 View last = getChildAt(numChildren - 1);
2761 while (last.getBottom() < listBottom) {
2762 final int lastVisiblePosition = mFirstPosition + numChildren - 1;
2763 if (lastVisiblePosition < mItemCount - 1) {
2764 last = addViewBelow(last, lastVisiblePosition);
2765 numChildren++;
2766 } else {
2767 break;
2768 }
2769 }
2770
2771 // may have brought in the last child of the list that is skinnier
2772 // than the fading edge, thereby leaving space at the end. need
2773 // to shift back
2774 if (last.getBottom() < listBottom) {
2775 offsetChildrenTopAndBottom(listBottom - last.getBottom());
2776 }
2777
2778 // top views may be panned off screen
2779 View first = getChildAt(0);
2780 while (first.getBottom() < listTop) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002781 AbsListView.LayoutParams layoutParams = (LayoutParams) first.getLayoutParams();
2782 if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) {
Romain Guy2d51bff2010-01-19 17:34:10 -08002783 detachViewFromParent(first);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002784 recycleBin.addScrapView(first);
2785 } else {
Romain Guy2d51bff2010-01-19 17:34:10 -08002786 removeViewInLayout(first);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 first = getChildAt(0);
2789 mFirstPosition++;
2790 }
2791 } else {
2792 // shifted items down
2793 View first = getChildAt(0);
2794
2795 // may need to pan views into top
2796 while ((first.getTop() > listTop) && (mFirstPosition > 0)) {
2797 first = addViewAbove(first, mFirstPosition);
2798 mFirstPosition--;
2799 }
2800
2801 // may have brought the very first child of the list in too far and
2802 // need to shift it back
2803 if (first.getTop() > listTop) {
2804 offsetChildrenTopAndBottom(listTop - first.getTop());
2805 }
2806
2807 int lastIndex = getChildCount() - 1;
2808 View last = getChildAt(lastIndex);
2809
2810 // bottom view may be panned off screen
2811 while (last.getTop() > listBottom) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002812 AbsListView.LayoutParams layoutParams = (LayoutParams) last.getLayoutParams();
2813 if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) {
Romain Guy2d51bff2010-01-19 17:34:10 -08002814 detachViewFromParent(last);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002815 recycleBin.addScrapView(last);
2816 } else {
Romain Guy2d51bff2010-01-19 17:34:10 -08002817 removeViewInLayout(last);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 last = getChildAt(--lastIndex);
2820 }
2821 }
2822 }
2823
2824 private View addViewAbove(View theView, int position) {
2825 int abovePosition = position - 1;
Romain Guy21875052010-01-06 18:48:08 -08002826 View view = obtainView(abovePosition, mIsScrap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 int edgeOfNewChild = theView.getTop() - mDividerHeight;
Romain Guy21875052010-01-06 18:48:08 -08002828 setupChild(view, abovePosition, edgeOfNewChild, false, mListPadding.left,
2829 false, mIsScrap[0]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 return view;
2831 }
2832
2833 private View addViewBelow(View theView, int position) {
2834 int belowPosition = position + 1;
Romain Guy21875052010-01-06 18:48:08 -08002835 View view = obtainView(belowPosition, mIsScrap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 int edgeOfNewChild = theView.getBottom() + mDividerHeight;
Romain Guy21875052010-01-06 18:48:08 -08002837 setupChild(view, belowPosition, edgeOfNewChild, true, mListPadding.left,
2838 false, mIsScrap[0]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 return view;
2840 }
2841
2842 /**
2843 * Indicates that the views created by the ListAdapter can contain focusable
2844 * items.
2845 *
2846 * @param itemsCanFocus true if items can get focus, false otherwise
2847 */
2848 public void setItemsCanFocus(boolean itemsCanFocus) {
2849 mItemsCanFocus = itemsCanFocus;
2850 if (!itemsCanFocus) {
2851 setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
2852 }
2853 }
2854
2855 /**
2856 * @return Whether the views created by the ListAdapter can contain focusable
2857 * items.
2858 */
2859 public boolean getItemsCanFocus() {
2860 return mItemsCanFocus;
2861 }
2862
Romain Guy2d6afea2009-05-11 15:19:21 -07002863 /**
2864 * @hide Pending API council approval.
2865 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 @Override
Romain Guy24443ea2009-05-11 11:56:30 -07002867 public boolean isOpaque() {
Romain Guy8f1344f2009-05-15 16:03:59 -07002868 return (mCachingStarted && mIsCacheColorOpaque && mDividerIsOpaque &&
2869 hasOpaqueScrollbars()) || super.isOpaque();
Romain Guy24443ea2009-05-11 11:56:30 -07002870 }
2871
2872 @Override
2873 public void setCacheColorHint(int color) {
Romain Guy8f1344f2009-05-15 16:03:59 -07002874 final boolean opaque = (color >>> 24) == 0xFF;
2875 mIsCacheColorOpaque = opaque;
2876 if (opaque) {
Romain Guya02903f2009-05-23 13:26:46 -07002877 if (mDividerPaint == null) {
2878 mDividerPaint = new Paint();
2879 }
Romain Guy8f1344f2009-05-15 16:03:59 -07002880 mDividerPaint.setColor(color);
2881 }
Romain Guy24443ea2009-05-11 11:56:30 -07002882 super.setCacheColorHint(color);
2883 }
2884
2885 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 protected void dispatchDraw(Canvas canvas) {
2887 // Draw the dividers
2888 final int dividerHeight = mDividerHeight;
2889
2890 if (dividerHeight > 0 && mDivider != null) {
2891 // Only modify the top and bottom in the loop, we set the left and right here
2892 final Rect bounds = mTempRect;
2893 bounds.left = mPaddingLeft;
2894 bounds.right = mRight - mLeft - mPaddingRight;
2895
2896 final int count = getChildCount();
2897 final int headerCount = mHeaderViewInfos.size();
2898 final int footerLimit = mItemCount - mFooterViewInfos.size() - 1;
2899 final boolean headerDividers = mHeaderDividersEnabled;
2900 final boolean footerDividers = mFooterDividersEnabled;
2901 final int first = mFirstPosition;
Romain Guy2bed2272009-03-24 18:23:21 -07002902 final boolean areAllItemsSelectable = mAreAllItemsSelectable;
2903 final ListAdapter adapter = mAdapter;
Romain Guye32edc62009-05-29 10:33:36 -07002904 // If the list is opaque *and* the background is not, we want to
2905 // fill a rect where the dividers would be for non-selectable items
2906 // If the list is opaque and the background is also opaque, we don't
2907 // need to draw anything since the background will do it for us
2908 final boolean fillForMissingDividers = isOpaque() && !super.isOpaque();
2909
2910 if (fillForMissingDividers && mDividerPaint == null && mIsCacheColorOpaque) {
Romain Guya02903f2009-05-23 13:26:46 -07002911 mDividerPaint = new Paint();
Romain Guye32edc62009-05-29 10:33:36 -07002912 mDividerPaint.setColor(getCacheColorHint());
Romain Guya02903f2009-05-23 13:26:46 -07002913 }
Romain Guy8f1344f2009-05-15 16:03:59 -07002914 final Paint paint = mDividerPaint;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915
2916 if (!mStackFromBottom) {
2917 int bottom;
Adam Powell0b8bb422010-02-08 14:30:45 -08002918 int listBottom = mBottom - mTop - mListPadding.bottom + mScrollY;
2919
2920 // Draw top divider for overscroll
2921 if (count > 0 && mScrollY < 0) {
2922 bounds.bottom = 0;
2923 bounds.top = -dividerHeight;
2924 drawDivider(canvas, bounds, -1);
2925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926
2927 for (int i = 0; i < count; i++) {
2928 if ((headerDividers || first + i >= headerCount) &&
2929 (footerDividers || first + i < footerLimit)) {
2930 View child = getChildAt(i);
2931 bottom = child.getBottom();
Romain Guy2bed2272009-03-24 18:23:21 -07002932 // Don't draw dividers next to items that are not enabled
Romain Guy8f1344f2009-05-15 16:03:59 -07002933 if (bottom < listBottom) {
2934 if ((areAllItemsSelectable ||
2935 (adapter.isEnabled(first + i) && (i == count - 1 ||
2936 adapter.isEnabled(first + i + 1))))) {
2937 bounds.top = bottom;
2938 bounds.bottom = bottom + dividerHeight;
2939 drawDivider(canvas, bounds, i);
Romain Guye32edc62009-05-29 10:33:36 -07002940 } else if (fillForMissingDividers) {
Romain Guy8f1344f2009-05-15 16:03:59 -07002941 bounds.top = bottom;
2942 bounds.bottom = bottom + dividerHeight;
2943 canvas.drawRect(bounds, paint);
2944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 }
2946 }
2947 }
2948 } else {
2949 int top;
2950 int listTop = mListPadding.top;
2951
2952 for (int i = 0; i < count; i++) {
2953 if ((headerDividers || first + i >= headerCount) &&
2954 (footerDividers || first + i < footerLimit)) {
2955 View child = getChildAt(i);
2956 top = child.getTop();
Romain Guy2bed2272009-03-24 18:23:21 -07002957 // Don't draw dividers next to items that are not enabled
Romain Guy8f1344f2009-05-15 16:03:59 -07002958 if (top > listTop) {
2959 if ((areAllItemsSelectable ||
2960 (adapter.isEnabled(first + i) && (i == count - 1 ||
2961 adapter.isEnabled(first + i + 1))))) {
2962 bounds.top = top - dividerHeight;
2963 bounds.bottom = top;
2964 // Give the method the child ABOVE the divider, so we
2965 // subtract one from our child
2966 // position. Give -1 when there is no child above the
2967 // divider.
2968 drawDivider(canvas, bounds, i - 1);
Romain Guye32edc62009-05-29 10:33:36 -07002969 } else if (fillForMissingDividers) {
Romain Guy8f1344f2009-05-15 16:03:59 -07002970 bounds.top = top - dividerHeight;
2971 bounds.bottom = top;
2972 canvas.drawRect(bounds, paint);
2973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 }
2975 }
2976 }
2977 }
2978 }
2979
2980 // Draw the indicators (these should be drawn above the dividers) and children
2981 super.dispatchDraw(canvas);
2982 }
2983
2984 /**
2985 * Draws a divider for the given child in the given bounds.
2986 *
2987 * @param canvas The canvas to draw to.
2988 * @param bounds The bounds of the divider.
2989 * @param childIndex The index of child (of the View) above the divider.
2990 * This will be -1 if there is no child above the divider to be
2991 * drawn.
2992 */
2993 void drawDivider(Canvas canvas, Rect bounds, int childIndex) {
2994 // This widget draws the same divider for all children
2995 final Drawable divider = mDivider;
2996 final boolean clipDivider = mClipDivider;
2997
2998 if (!clipDivider) {
2999 divider.setBounds(bounds);
3000 } else {
3001 canvas.save();
3002 canvas.clipRect(bounds);
3003 }
3004
3005 divider.draw(canvas);
3006
3007 if (clipDivider) {
3008 canvas.restore();
3009 }
3010 }
3011
3012 /**
3013 * Returns the drawable that will be drawn between each item in the list.
3014 *
3015 * @return the current drawable drawn between list elements
3016 */
3017 public Drawable getDivider() {
3018 return mDivider;
3019 }
3020
3021 /**
3022 * Sets the drawable that will be drawn between each item in the list. If the drawable does
3023 * not have an intrinsic height, you should also call {@link #setDividerHeight(int)}
3024 *
3025 * @param divider The drawable to use.
3026 */
3027 public void setDivider(Drawable divider) {
3028 if (divider != null) {
3029 mDividerHeight = divider.getIntrinsicHeight();
3030 mClipDivider = divider instanceof ColorDrawable;
3031 } else {
3032 mDividerHeight = 0;
3033 mClipDivider = false;
3034 }
3035 mDivider = divider;
Romain Guy24443ea2009-05-11 11:56:30 -07003036 mDividerIsOpaque = divider == null || divider.getOpacity() == PixelFormat.OPAQUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037 requestLayoutIfNecessary();
3038 }
3039
3040 /**
3041 * @return Returns the height of the divider that will be drawn between each item in the list.
3042 */
3043 public int getDividerHeight() {
3044 return mDividerHeight;
3045 }
3046
3047 /**
3048 * Sets the height of the divider that will be drawn between each item in the list. Calling
3049 * this will override the intrinsic height as set by {@link #setDivider(Drawable)}
3050 *
3051 * @param height The new height of the divider in pixels.
3052 */
3053 public void setDividerHeight(int height) {
3054 mDividerHeight = height;
3055 requestLayoutIfNecessary();
3056 }
3057
3058 /**
3059 * Enables or disables the drawing of the divider for header views.
3060 *
3061 * @param headerDividersEnabled True to draw the headers, false otherwise.
3062 *
3063 * @see #setFooterDividersEnabled(boolean)
3064 * @see #addHeaderView(android.view.View)
3065 */
3066 public void setHeaderDividersEnabled(boolean headerDividersEnabled) {
3067 mHeaderDividersEnabled = headerDividersEnabled;
3068 invalidate();
3069 }
3070
3071 /**
3072 * Enables or disables the drawing of the divider for footer views.
3073 *
3074 * @param footerDividersEnabled True to draw the footers, false otherwise.
3075 *
3076 * @see #setHeaderDividersEnabled(boolean)
3077 * @see #addFooterView(android.view.View)
3078 */
3079 public void setFooterDividersEnabled(boolean footerDividersEnabled) {
3080 mFooterDividersEnabled = footerDividersEnabled;
3081 invalidate();
3082 }
3083
3084 @Override
3085 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3086 super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
3087
3088 int closetChildIndex = -1;
3089 if (gainFocus && previouslyFocusedRect != null) {
3090 previouslyFocusedRect.offset(mScrollX, mScrollY);
3091
Adam Powellc854f282009-12-16 14:11:53 -08003092 final ListAdapter adapter = mAdapter;
Adam Powelld7507832010-02-18 15:40:33 -08003093 // Don't cache the result of getChildCount or mFirstPosition here,
3094 // it could change in layoutChildren.
3095 if (adapter.getCount() < getChildCount() + mFirstPosition) {
Adam Powellc854f282009-12-16 14:11:53 -08003096 mLayoutMode = LAYOUT_NORMAL;
3097 layoutChildren();
3098 }
3099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100 // figure out which item should be selected based on previously
3101 // focused rect
3102 Rect otherRect = mTempRect;
3103 int minDistance = Integer.MAX_VALUE;
3104 final int childCount = getChildCount();
Adam Powelld7507832010-02-18 15:40:33 -08003105 final int firstPosition = mFirstPosition;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106
3107 for (int i = 0; i < childCount; i++) {
3108 // only consider selectable views
3109 if (!adapter.isEnabled(firstPosition + i)) {
3110 continue;
3111 }
3112
3113 View other = getChildAt(i);
3114 other.getDrawingRect(otherRect);
3115 offsetDescendantRectToMyCoords(other, otherRect);
3116 int distance = getDistance(previouslyFocusedRect, otherRect, direction);
3117
3118 if (distance < minDistance) {
3119 minDistance = distance;
3120 closetChildIndex = i;
3121 }
3122 }
3123 }
3124
3125 if (closetChildIndex >= 0) {
3126 setSelection(closetChildIndex + mFirstPosition);
3127 } else {
3128 requestLayout();
3129 }
3130 }
3131
3132
3133 /*
3134 * (non-Javadoc)
3135 *
3136 * Children specified in XML are assumed to be header views. After we have
3137 * parsed them move them out of the children list and into mHeaderViews.
3138 */
3139 @Override
3140 protected void onFinishInflate() {
3141 super.onFinishInflate();
3142
3143 int count = getChildCount();
3144 if (count > 0) {
3145 for (int i = 0; i < count; ++i) {
3146 addHeaderView(getChildAt(i));
3147 }
3148 removeAllViews();
3149 }
3150 }
3151
3152 /* (non-Javadoc)
3153 * @see android.view.View#findViewById(int)
3154 * First look in our children, then in any header and footer views that may be scrolled off.
3155 */
3156 @Override
3157 protected View findViewTraversal(int id) {
3158 View v;
3159 v = super.findViewTraversal(id);
3160 if (v == null) {
3161 v = findViewInHeadersOrFooters(mHeaderViewInfos, id);
3162 if (v != null) {
3163 return v;
3164 }
3165 v = findViewInHeadersOrFooters(mFooterViewInfos, id);
3166 if (v != null) {
3167 return v;
3168 }
3169 }
3170 return v;
3171 }
3172
3173 /* (non-Javadoc)
3174 *
3175 * Look in the passed in list of headers or footers for the view.
3176 */
3177 View findViewInHeadersOrFooters(ArrayList<FixedViewInfo> where, int id) {
3178 if (where != null) {
3179 int len = where.size();
3180 View v;
3181
3182 for (int i = 0; i < len; i++) {
3183 v = where.get(i).view;
3184
3185 if (!v.isRootNamespace()) {
3186 v = v.findViewById(id);
3187
3188 if (v != null) {
3189 return v;
3190 }
3191 }
3192 }
3193 }
3194 return null;
3195 }
3196
3197 /* (non-Javadoc)
3198 * @see android.view.View#findViewWithTag(String)
3199 * First look in our children, then in any header and footer views that may be scrolled off.
3200 */
3201 @Override
3202 protected View findViewWithTagTraversal(Object tag) {
3203 View v;
3204 v = super.findViewWithTagTraversal(tag);
3205 if (v == null) {
3206 v = findViewTagInHeadersOrFooters(mHeaderViewInfos, tag);
3207 if (v != null) {
3208 return v;
3209 }
3210
3211 v = findViewTagInHeadersOrFooters(mFooterViewInfos, tag);
3212 if (v != null) {
3213 return v;
3214 }
3215 }
3216 return v;
3217 }
3218
3219 /* (non-Javadoc)
3220 *
3221 * Look in the passed in list of headers or footers for the view with the tag.
3222 */
3223 View findViewTagInHeadersOrFooters(ArrayList<FixedViewInfo> where, Object tag) {
3224 if (where != null) {
3225 int len = where.size();
3226 View v;
3227
3228 for (int i = 0; i < len; i++) {
3229 v = where.get(i).view;
3230
3231 if (!v.isRootNamespace()) {
3232 v = v.findViewWithTag(tag);
3233
3234 if (v != null) {
3235 return v;
3236 }
3237 }
3238 }
3239 }
3240 return null;
3241 }
3242
3243 @Override
3244 public boolean onTouchEvent(MotionEvent ev) {
3245 if (mItemsCanFocus && ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
3246 // Don't handle edge touches immediately -- they may actually belong to one of our
3247 // descendants.
3248 return false;
3249 }
3250 return super.onTouchEvent(ev);
3251 }
3252
3253 /**
3254 * @see #setChoiceMode(int)
3255 *
3256 * @return The current choice mode
3257 */
3258 public int getChoiceMode() {
3259 return mChoiceMode;
3260 }
3261
3262 /**
3263 * Defines the choice behavior for the List. By default, Lists do not have any choice behavior
3264 * ({@link #CHOICE_MODE_NONE}). By setting the choiceMode to {@link #CHOICE_MODE_SINGLE}, the
3265 * List allows up to one item to be in a chosen state. By setting the choiceMode to
3266 * {@link #CHOICE_MODE_MULTIPLE}, the list allows any number of items to be chosen.
3267 *
3268 * @param choiceMode One of {@link #CHOICE_MODE_NONE}, {@link #CHOICE_MODE_SINGLE}, or
3269 * {@link #CHOICE_MODE_MULTIPLE}
3270 */
3271 public void setChoiceMode(int choiceMode) {
3272 mChoiceMode = choiceMode;
3273 if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates == null) {
3274 mCheckStates = new SparseBooleanArray();
3275 }
3276 }
3277
3278 @Override
3279 public boolean performItemClick(View view, int position, long id) {
3280 boolean handled = false;
3281
3282 if (mChoiceMode != CHOICE_MODE_NONE) {
3283 handled = true;
3284
3285 if (mChoiceMode == CHOICE_MODE_MULTIPLE) {
3286 boolean oldValue = mCheckStates.get(position, false);
3287 mCheckStates.put(position, !oldValue);
3288 } else {
3289 boolean oldValue = mCheckStates.get(position, false);
3290 if (!oldValue) {
3291 mCheckStates.clear();
3292 mCheckStates.put(position, true);
3293 }
3294 }
3295
3296 mDataChanged = true;
3297 rememberSyncState();
3298 requestLayout();
3299 }
3300
3301 handled |= super.performItemClick(view, position, id);
3302
3303 return handled;
3304 }
3305
3306 /**
3307 * Sets the checked state of the specified position. The is only valid if
3308 * the choice mode has been set to {@link #CHOICE_MODE_SINGLE} or
3309 * {@link #CHOICE_MODE_MULTIPLE}.
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -08003310 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 * @param position The item whose checked state is to be checked
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -08003312 * @param value The new checked state for the item
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 */
3314 public void setItemChecked(int position, boolean value) {
3315 if (mChoiceMode == CHOICE_MODE_NONE) {
3316 return;
3317 }
3318
3319 if (mChoiceMode == CHOICE_MODE_MULTIPLE) {
3320 mCheckStates.put(position, value);
3321 } else {
Brett Chabot845df822009-08-03 16:40:02 -07003322 // Clear all values if we're checking something, or unchecking the currently
3323 // selected item
3324 if (value || isItemChecked(position)) {
3325 mCheckStates.clear();
3326 }
Romain Guy8842f0b2009-06-24 12:53:54 -07003327 // this may end up selecting the value we just cleared but this way
Brett Chabot845df822009-08-03 16:40:02 -07003328 // we ensure length of mCheckStates is 1, a fact getCheckedItemPosition relies on
Romain Guy8842f0b2009-06-24 12:53:54 -07003329 if (value) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 mCheckStates.put(position, true);
3331 }
3332 }
3333
3334 // Do not generate a data change while we are in the layout phase
3335 if (!mInLayout && !mBlockLayoutRequests) {
3336 mDataChanged = true;
3337 rememberSyncState();
3338 requestLayout();
3339 }
3340 }
3341
3342 /**
3343 * Returns the checked state of the specified position. The result is only
Kenny Rootabca4e82009-06-09 12:07:28 -05003344 * valid if the choice mode has been set to {@link #CHOICE_MODE_SINGLE}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 * or {@link #CHOICE_MODE_MULTIPLE}.
3346 *
3347 * @param position The item whose checked state to return
Kenny Rootabca4e82009-06-09 12:07:28 -05003348 * @return The item's checked state or <code>false</code> if choice mode
3349 * is invalid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 *
3351 * @see #setChoiceMode(int)
3352 */
3353 public boolean isItemChecked(int position) {
3354 if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null) {
3355 return mCheckStates.get(position);
3356 }
3357
3358 return false;
3359 }
3360
3361 /**
3362 * Returns the currently checked item. The result is only valid if the choice
Kenny Rootabca4e82009-06-09 12:07:28 -05003363 * mode has been set to {@link #CHOICE_MODE_SINGLE}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 *
3365 * @return The position of the currently checked item or
3366 * {@link #INVALID_POSITION} if nothing is selected
3367 *
3368 * @see #setChoiceMode(int)
3369 */
3370 public int getCheckedItemPosition() {
3371 if (mChoiceMode == CHOICE_MODE_SINGLE && mCheckStates != null && mCheckStates.size() == 1) {
3372 return mCheckStates.keyAt(0);
3373 }
3374
3375 return INVALID_POSITION;
3376 }
3377
3378 /**
3379 * Returns the set of checked items in the list. The result is only valid if
Kenny Rootabca4e82009-06-09 12:07:28 -05003380 * the choice mode has not been set to {@link #CHOICE_MODE_NONE}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 *
3382 * @return A SparseBooleanArray which will return true for each call to
Kenny Rootabca4e82009-06-09 12:07:28 -05003383 * get(int position) where position is a position in the list,
3384 * or <code>null</code> if the choice mode is set to
3385 * {@link #CHOICE_MODE_NONE}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 */
3387 public SparseBooleanArray getCheckedItemPositions() {
3388 if (mChoiceMode != CHOICE_MODE_NONE) {
3389 return mCheckStates;
3390 }
3391 return null;
3392 }
3393
3394 /**
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -08003395 * Returns the set of checked items ids. The result is only valid if the
3396 * choice mode has not been set to {@link #CHOICE_MODE_SINGLE}.
3397 *
3398 * @return A new array which contains the id of each checked item in the
3399 * list.
Romain Guyad28bed2009-04-01 11:46:43 -07003400 */
3401 public long[] getCheckItemIds() {
3402 if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null && mAdapter != null) {
3403 final SparseBooleanArray states = mCheckStates;
3404 final int count = states.size();
3405 final long[] ids = new long[count];
3406 final ListAdapter adapter = mAdapter;
3407
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -08003408 int checkedCount = 0;
Romain Guyad28bed2009-04-01 11:46:43 -07003409 for (int i = 0; i < count; i++) {
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -08003410 if (states.valueAt(i)) {
3411 ids[checkedCount++] = adapter.getItemId(states.keyAt(i));
3412 }
Romain Guyad28bed2009-04-01 11:46:43 -07003413 }
3414
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -08003415 // Trim array if needed. mCheckStates may contain false values
3416 // resulting in checkedCount being smaller than count.
3417 if (checkedCount == count) {
3418 return ids;
3419 } else {
3420 final long[] result = new long[checkedCount];
3421 System.arraycopy(ids, 0, result, 0, checkedCount);
3422
3423 return result;
3424 }
Romain Guyad28bed2009-04-01 11:46:43 -07003425 }
3426
3427 return new long[0];
3428 }
3429
3430 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 * Clear any choices previously set
3432 */
3433 public void clearChoices() {
3434 if (mCheckStates != null) {
3435 mCheckStates.clear();
3436 }
3437 }
3438
3439 static class SavedState extends BaseSavedState {
3440 SparseBooleanArray checkState;
3441
3442 /**
3443 * Constructor called from {@link ListView#onSaveInstanceState()}
3444 */
3445 SavedState(Parcelable superState, SparseBooleanArray checkState) {
3446 super(superState);
3447 this.checkState = checkState;
3448 }
3449
3450 /**
3451 * Constructor called from {@link #CREATOR}
3452 */
3453 private SavedState(Parcel in) {
3454 super(in);
3455 checkState = in.readSparseBooleanArray();
3456 }
3457
3458 @Override
3459 public void writeToParcel(Parcel out, int flags) {
3460 super.writeToParcel(out, flags);
3461 out.writeSparseBooleanArray(checkState);
3462 }
3463
3464 @Override
3465 public String toString() {
3466 return "ListView.SavedState{"
3467 + Integer.toHexString(System.identityHashCode(this))
3468 + " checkState=" + checkState + "}";
3469 }
3470
3471 public static final Parcelable.Creator<SavedState> CREATOR
3472 = new Parcelable.Creator<SavedState>() {
3473 public SavedState createFromParcel(Parcel in) {
3474 return new SavedState(in);
3475 }
3476
3477 public SavedState[] newArray(int size) {
3478 return new SavedState[size];
3479 }
3480 };
3481 }
3482
3483 @Override
3484 public Parcelable onSaveInstanceState() {
3485 Parcelable superState = super.onSaveInstanceState();
3486 return new SavedState(superState, mCheckStates);
3487 }
3488
3489 @Override
3490 public void onRestoreInstanceState(Parcelable state) {
3491 SavedState ss = (SavedState) state;
3492
3493 super.onRestoreInstanceState(ss.getSuperState());
3494
3495 if (ss.checkState != null) {
3496 mCheckStates = ss.checkState;
3497 }
3498
3499 }
3500}