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