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