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