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