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