ListView.java revision 56032a37df89511c8d3b3b3c79818e2c86dedb92
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     * Sets the selected item and positions the selection y pixels from the top edge
1896     * of the ListView. (If in touch mode, the item will not be selected but it will
1897     * still be positioned appropriately.)
1898     *
1899     * @param position Index (starting at 0) of the data item to be selected.
1900     * @param y The distance from the top edge of the ListView (plus padding) that the
1901     *        item will be positioned.
1902     */
1903    public void setSelectionFromTop(int position, int y) {
1904        if (mAdapter == null) {
1905            return;
1906        }
1907
1908        if (!isInTouchMode()) {
1909            position = lookForSelectablePosition(position, true);
1910            if (position >= 0) {
1911                setNextSelectedPositionInt(position);
1912            }
1913        } else {
1914            mResurrectToPosition = position;
1915        }
1916
1917        if (position >= 0) {
1918            mLayoutMode = LAYOUT_SPECIFIC;
1919            mSpecificTop = mListPadding.top + y;
1920
1921            if (mNeedSync) {
1922                mSyncPosition = position;
1923                mSyncRowId = mAdapter.getItemId(position);
1924            }
1925
1926            if (mPositionScroller != null) {
1927                mPositionScroller.stop();
1928            }
1929            requestLayout();
1930        }
1931    }
1932
1933    /**
1934     * Makes the item at the supplied position selected.
1935     *
1936     * @param position the position of the item to select
1937     */
1938    @Override
1939    void setSelectionInt(int position) {
1940        setNextSelectedPositionInt(position);
1941        boolean awakeScrollbars = false;
1942
1943        final int selectedPosition = mSelectedPosition;
1944
1945        if (selectedPosition >= 0) {
1946            if (position == selectedPosition - 1) {
1947                awakeScrollbars = true;
1948            } else if (position == selectedPosition + 1) {
1949                awakeScrollbars = true;
1950            }
1951        }
1952
1953        if (mPositionScroller != null) {
1954            mPositionScroller.stop();
1955        }
1956
1957        layoutChildren();
1958
1959        if (awakeScrollbars) {
1960            awakenScrollBars();
1961        }
1962    }
1963
1964    /**
1965     * Find a position that can be selected (i.e., is not a separator).
1966     *
1967     * @param position The starting position to look at.
1968     * @param lookDown Whether to look down for other positions.
1969     * @return The next selectable position starting at position and then searching either up or
1970     *         down. Returns {@link #INVALID_POSITION} if nothing can be found.
1971     */
1972    @Override
1973    int lookForSelectablePosition(int position, boolean lookDown) {
1974        final ListAdapter adapter = mAdapter;
1975        if (adapter == null || isInTouchMode()) {
1976            return INVALID_POSITION;
1977        }
1978
1979        final int count = adapter.getCount();
1980        if (!mAreAllItemsSelectable) {
1981            if (lookDown) {
1982                position = Math.max(0, position);
1983                while (position < count && !adapter.isEnabled(position)) {
1984                    position++;
1985                }
1986            } else {
1987                position = Math.min(position, count - 1);
1988                while (position >= 0 && !adapter.isEnabled(position)) {
1989                    position--;
1990                }
1991            }
1992        }
1993
1994        if (position < 0 || position >= count) {
1995            return INVALID_POSITION;
1996        }
1997
1998        return position;
1999    }
2000
2001    /**
2002     * Find a position that can be selected (i.e., is not a separator). If there
2003     * are no selectable positions in the specified direction from the starting
2004     * position, searches in the opposite direction from the starting position
2005     * to the current position.
2006     *
2007     * @param current the current position
2008     * @param position the starting position
2009     * @param lookDown whether to look down for other positions
2010     * @return the next selectable position, or {@link #INVALID_POSITION} if
2011     *         nothing can be found
2012     */
2013    int lookForSelectablePositionAfter(int current, int position, boolean lookDown) {
2014        final ListAdapter adapter = mAdapter;
2015        if (adapter == null || isInTouchMode()) {
2016            return INVALID_POSITION;
2017        }
2018
2019        // First check after the starting position in the specified direction.
2020        final int after = lookForSelectablePosition(position, lookDown);
2021        if (after != INVALID_POSITION) {
2022            return after;
2023        }
2024
2025        // Then check between the starting position and the current position.
2026        final int count = adapter.getCount();
2027        current = MathUtils.constrain(current, -1, count - 1);
2028        if (lookDown) {
2029            position = Math.min(position - 1, count - 1);
2030            while ((position > current) && !adapter.isEnabled(position)) {
2031                position--;
2032            }
2033            if (position <= current) {
2034                return INVALID_POSITION;
2035            }
2036        } else {
2037            position = Math.max(0, position + 1);
2038            while ((position < current) && !adapter.isEnabled(position)) {
2039                position++;
2040            }
2041            if (position >= current) {
2042                return INVALID_POSITION;
2043            }
2044        }
2045
2046        return position;
2047    }
2048
2049    /**
2050     * setSelectionAfterHeaderView set the selection to be the first list item
2051     * after the header views.
2052     */
2053    public void setSelectionAfterHeaderView() {
2054        final int count = mHeaderViewInfos.size();
2055        if (count > 0) {
2056            mNextSelectedPosition = 0;
2057            return;
2058        }
2059
2060        if (mAdapter != null) {
2061            setSelection(count);
2062        } else {
2063            mNextSelectedPosition = count;
2064            mLayoutMode = LAYOUT_SET_SELECTION;
2065        }
2066
2067    }
2068
2069    @Override
2070    public boolean dispatchKeyEvent(KeyEvent event) {
2071        // Dispatch in the normal way
2072        boolean handled = super.dispatchKeyEvent(event);
2073        if (!handled) {
2074            // If we didn't handle it...
2075            View focused = getFocusedChild();
2076            if (focused != null && event.getAction() == KeyEvent.ACTION_DOWN) {
2077                // ... and our focused child didn't handle it
2078                // ... give it to ourselves so we can scroll if necessary
2079                handled = onKeyDown(event.getKeyCode(), event);
2080            }
2081        }
2082        return handled;
2083    }
2084
2085    @Override
2086    public boolean onKeyDown(int keyCode, KeyEvent event) {
2087        return commonKey(keyCode, 1, event);
2088    }
2089
2090    @Override
2091    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2092        return commonKey(keyCode, repeatCount, event);
2093    }
2094
2095    @Override
2096    public boolean onKeyUp(int keyCode, KeyEvent event) {
2097        return commonKey(keyCode, 1, event);
2098    }
2099
2100    private boolean commonKey(int keyCode, int count, KeyEvent event) {
2101        if (mAdapter == null || !isAttachedToWindow()) {
2102            return false;
2103        }
2104
2105        if (mDataChanged) {
2106            layoutChildren();
2107        }
2108
2109        boolean handled = false;
2110        int action = event.getAction();
2111
2112        if (action != KeyEvent.ACTION_UP) {
2113            switch (keyCode) {
2114            case KeyEvent.KEYCODE_DPAD_UP:
2115                if (event.hasNoModifiers()) {
2116                    handled = resurrectSelectionIfNeeded();
2117                    if (!handled) {
2118                        while (count-- > 0) {
2119                            if (arrowScroll(FOCUS_UP)) {
2120                                handled = true;
2121                            } else {
2122                                break;
2123                            }
2124                        }
2125                    }
2126                } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
2127                    handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_UP);
2128                }
2129                break;
2130
2131            case KeyEvent.KEYCODE_DPAD_DOWN:
2132                if (event.hasNoModifiers()) {
2133                    handled = resurrectSelectionIfNeeded();
2134                    if (!handled) {
2135                        while (count-- > 0) {
2136                            if (arrowScroll(FOCUS_DOWN)) {
2137                                handled = true;
2138                            } else {
2139                                break;
2140                            }
2141                        }
2142                    }
2143                } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
2144                    handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_DOWN);
2145                }
2146                break;
2147
2148            case KeyEvent.KEYCODE_DPAD_LEFT:
2149                if (event.hasNoModifiers()) {
2150                    handled = handleHorizontalFocusWithinListItem(View.FOCUS_LEFT);
2151                }
2152                break;
2153
2154            case KeyEvent.KEYCODE_DPAD_RIGHT:
2155                if (event.hasNoModifiers()) {
2156                    handled = handleHorizontalFocusWithinListItem(View.FOCUS_RIGHT);
2157                }
2158                break;
2159
2160            case KeyEvent.KEYCODE_DPAD_CENTER:
2161            case KeyEvent.KEYCODE_ENTER:
2162                if (event.hasNoModifiers()) {
2163                    handled = resurrectSelectionIfNeeded();
2164                    if (!handled
2165                            && event.getRepeatCount() == 0 && getChildCount() > 0) {
2166                        keyPressed();
2167                        handled = true;
2168                    }
2169                }
2170                break;
2171
2172            case KeyEvent.KEYCODE_SPACE:
2173                if (mPopup == null || !mPopup.isShowing()) {
2174                    if (event.hasNoModifiers()) {
2175                        handled = resurrectSelectionIfNeeded() || pageScroll(FOCUS_DOWN);
2176                    } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
2177                        handled = resurrectSelectionIfNeeded() || pageScroll(FOCUS_UP);
2178                    }
2179                    handled = true;
2180                }
2181                break;
2182
2183            case KeyEvent.KEYCODE_PAGE_UP:
2184                if (event.hasNoModifiers()) {
2185                    handled = resurrectSelectionIfNeeded() || pageScroll(FOCUS_UP);
2186                } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
2187                    handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_UP);
2188                }
2189                break;
2190
2191            case KeyEvent.KEYCODE_PAGE_DOWN:
2192                if (event.hasNoModifiers()) {
2193                    handled = resurrectSelectionIfNeeded() || pageScroll(FOCUS_DOWN);
2194                } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
2195                    handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_DOWN);
2196                }
2197                break;
2198
2199            case KeyEvent.KEYCODE_MOVE_HOME:
2200                if (event.hasNoModifiers()) {
2201                    handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_UP);
2202                }
2203                break;
2204
2205            case KeyEvent.KEYCODE_MOVE_END:
2206                if (event.hasNoModifiers()) {
2207                    handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_DOWN);
2208                }
2209                break;
2210
2211            case KeyEvent.KEYCODE_TAB:
2212                // XXX Sometimes it is useful to be able to TAB through the items in
2213                //     a ListView sequentially.  Unfortunately this can create an
2214                //     asymmetry in TAB navigation order unless the list selection
2215                //     always reverts to the top or bottom when receiving TAB focus from
2216                //     another widget.  Leaving this behavior disabled for now but
2217                //     perhaps it should be configurable (and more comprehensive).
2218                if (false) {
2219                    if (event.hasNoModifiers()) {
2220                        handled = resurrectSelectionIfNeeded() || arrowScroll(FOCUS_DOWN);
2221                    } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
2222                        handled = resurrectSelectionIfNeeded() || arrowScroll(FOCUS_UP);
2223                    }
2224                }
2225                break;
2226            }
2227        }
2228
2229        if (handled) {
2230            return true;
2231        }
2232
2233        if (sendToTextFilter(keyCode, count, event)) {
2234            return true;
2235        }
2236
2237        switch (action) {
2238            case KeyEvent.ACTION_DOWN:
2239                return super.onKeyDown(keyCode, event);
2240
2241            case KeyEvent.ACTION_UP:
2242                return super.onKeyUp(keyCode, event);
2243
2244            case KeyEvent.ACTION_MULTIPLE:
2245                return super.onKeyMultiple(keyCode, count, event);
2246
2247            default: // shouldn't happen
2248                return false;
2249        }
2250    }
2251
2252    /**
2253     * Scrolls up or down by the number of items currently present on screen.
2254     *
2255     * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
2256     * @return whether selection was moved
2257     */
2258    boolean pageScroll(int direction) {
2259        final int nextPage;
2260        final boolean down;
2261
2262        if (direction == FOCUS_UP) {
2263            nextPage = Math.max(0, mSelectedPosition - getChildCount() - 1);
2264            down = false;
2265        } else if (direction == FOCUS_DOWN) {
2266            nextPage = Math.min(mItemCount - 1, mSelectedPosition + getChildCount() - 1);
2267            down = true;
2268        } else {
2269            return false;
2270        }
2271
2272        if (nextPage >= 0) {
2273            final int position = lookForSelectablePositionAfter(mSelectedPosition, nextPage, down);
2274            if (position >= 0) {
2275                mLayoutMode = LAYOUT_SPECIFIC;
2276                mSpecificTop = mPaddingTop + getVerticalFadingEdgeLength();
2277
2278                if (down && (position > (mItemCount - getChildCount()))) {
2279                    mLayoutMode = LAYOUT_FORCE_BOTTOM;
2280                }
2281
2282                if (!down && (position < getChildCount())) {
2283                    mLayoutMode = LAYOUT_FORCE_TOP;
2284                }
2285
2286                setSelectionInt(position);
2287                invokeOnItemScrollListener();
2288                if (!awakenScrollBars()) {
2289                    invalidate();
2290                }
2291
2292                return true;
2293            }
2294        }
2295
2296        return false;
2297    }
2298
2299    /**
2300     * Go to the last or first item if possible (not worrying about panning
2301     * across or navigating within the internal focus of the currently selected
2302     * item.)
2303     *
2304     * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
2305     * @return whether selection was moved
2306     */
2307    boolean fullScroll(int direction) {
2308        boolean moved = false;
2309        if (direction == FOCUS_UP) {
2310            if (mSelectedPosition != 0) {
2311                final int position = lookForSelectablePositionAfter(mSelectedPosition, 0, true);
2312                if (position >= 0) {
2313                    mLayoutMode = LAYOUT_FORCE_TOP;
2314                    setSelectionInt(position);
2315                    invokeOnItemScrollListener();
2316                }
2317                moved = true;
2318            }
2319        } else if (direction == FOCUS_DOWN) {
2320            final int lastItem = (mItemCount - 1);
2321            if (mSelectedPosition < lastItem) {
2322                final int position = lookForSelectablePositionAfter(
2323                        mSelectedPosition, lastItem, false);
2324                if (position >= 0) {
2325                    mLayoutMode = LAYOUT_FORCE_BOTTOM;
2326                    setSelectionInt(position);
2327                    invokeOnItemScrollListener();
2328                }
2329                moved = true;
2330            }
2331        }
2332
2333        if (moved && !awakenScrollBars()) {
2334            awakenScrollBars();
2335            invalidate();
2336        }
2337
2338        return moved;
2339    }
2340
2341    /**
2342     * To avoid horizontal focus searches changing the selected item, we
2343     * manually focus search within the selected item (as applicable), and
2344     * prevent focus from jumping to something within another item.
2345     * @param direction one of {View.FOCUS_LEFT, View.FOCUS_RIGHT}
2346     * @return Whether this consumes the key event.
2347     */
2348    private boolean handleHorizontalFocusWithinListItem(int direction) {
2349        if (direction != View.FOCUS_LEFT && direction != View.FOCUS_RIGHT)  {
2350            throw new IllegalArgumentException("direction must be one of"
2351                    + " {View.FOCUS_LEFT, View.FOCUS_RIGHT}");
2352        }
2353
2354        final int numChildren = getChildCount();
2355        if (mItemsCanFocus && numChildren > 0 && mSelectedPosition != INVALID_POSITION) {
2356            final View selectedView = getSelectedView();
2357            if (selectedView != null && selectedView.hasFocus() &&
2358                    selectedView instanceof ViewGroup) {
2359
2360                final View currentFocus = selectedView.findFocus();
2361                final View nextFocus = FocusFinder.getInstance().findNextFocus(
2362                        (ViewGroup) selectedView, currentFocus, direction);
2363                if (nextFocus != null) {
2364                    // do the math to get interesting rect in next focus' coordinates
2365                    currentFocus.getFocusedRect(mTempRect);
2366                    offsetDescendantRectToMyCoords(currentFocus, mTempRect);
2367                    offsetRectIntoDescendantCoords(nextFocus, mTempRect);
2368                    if (nextFocus.requestFocus(direction, mTempRect)) {
2369                        return true;
2370                    }
2371                }
2372                // we are blocking the key from being handled (by returning true)
2373                // if the global result is going to be some other view within this
2374                // list.  this is to acheive the overall goal of having
2375                // horizontal d-pad navigation remain in the current item.
2376                final View globalNextFocus = FocusFinder.getInstance().findNextFocus(
2377                        (ViewGroup) getRootView(), currentFocus, direction);
2378                if (globalNextFocus != null) {
2379                    return isViewAncestorOf(globalNextFocus, this);
2380                }
2381            }
2382        }
2383        return false;
2384    }
2385
2386    /**
2387     * Scrolls to the next or previous item if possible.
2388     *
2389     * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
2390     *
2391     * @return whether selection was moved
2392     */
2393    boolean arrowScroll(int direction) {
2394        try {
2395            mInLayout = true;
2396            final boolean handled = arrowScrollImpl(direction);
2397            if (handled) {
2398                playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2399            }
2400            return handled;
2401        } finally {
2402            mInLayout = false;
2403        }
2404    }
2405
2406    /**
2407     * Used by {@link #arrowScrollImpl(int)} to help determine the next selected position
2408     * to move to. This return a position in the direction given if the selected item
2409     * is fully visible.
2410     *
2411     * @param selectedView Current selected view to move from
2412     * @param selectedPos Current selected position to move from
2413     * @param direction Direction to move in
2414     * @return Desired selected position after moving in the given direction
2415     */
2416    private final int nextSelectedPositionForDirection(
2417            View selectedView, int selectedPos, int direction) {
2418        int nextSelected;
2419
2420        if (direction == View.FOCUS_DOWN) {
2421            final int listBottom = getHeight() - mListPadding.bottom;
2422            if (selectedView != null && selectedView.getBottom() <= listBottom) {
2423                nextSelected = selectedPos != INVALID_POSITION && selectedPos >= mFirstPosition ?
2424                        selectedPos + 1 :
2425                        mFirstPosition;
2426            } else {
2427                return INVALID_POSITION;
2428            }
2429        } else {
2430            final int listTop = mListPadding.top;
2431            if (selectedView != null && selectedView.getTop() >= listTop) {
2432                final int lastPos = mFirstPosition + getChildCount() - 1;
2433                nextSelected = selectedPos != INVALID_POSITION && selectedPos <= lastPos ?
2434                        selectedPos - 1 :
2435                        lastPos;
2436            } else {
2437                return INVALID_POSITION;
2438            }
2439        }
2440
2441        if (nextSelected < 0 || nextSelected >= mAdapter.getCount()) {
2442            return INVALID_POSITION;
2443        }
2444        return lookForSelectablePosition(nextSelected, direction == View.FOCUS_DOWN);
2445    }
2446
2447    /**
2448     * Handle an arrow scroll going up or down.  Take into account whether items are selectable,
2449     * whether there are focusable items etc.
2450     *
2451     * @param direction Either {@link android.view.View#FOCUS_UP} or {@link android.view.View#FOCUS_DOWN}.
2452     * @return Whether any scrolling, selection or focus change occured.
2453     */
2454    private boolean arrowScrollImpl(int direction) {
2455        if (getChildCount() <= 0) {
2456            return false;
2457        }
2458
2459        View selectedView = getSelectedView();
2460        int selectedPos = mSelectedPosition;
2461
2462        int nextSelectedPosition = nextSelectedPositionForDirection(selectedView, selectedPos, direction);
2463        int amountToScroll = amountToScroll(direction, nextSelectedPosition);
2464
2465        // if we are moving focus, we may OVERRIDE the default behavior
2466        final ArrowScrollFocusResult focusResult = mItemsCanFocus ? arrowScrollFocused(direction) : null;
2467        if (focusResult != null) {
2468            nextSelectedPosition = focusResult.getSelectedPosition();
2469            amountToScroll = focusResult.getAmountToScroll();
2470        }
2471
2472        boolean needToRedraw = focusResult != null;
2473        if (nextSelectedPosition != INVALID_POSITION) {
2474            handleNewSelectionChange(selectedView, direction, nextSelectedPosition, focusResult != null);
2475            setSelectedPositionInt(nextSelectedPosition);
2476            setNextSelectedPositionInt(nextSelectedPosition);
2477            selectedView = getSelectedView();
2478            selectedPos = nextSelectedPosition;
2479            if (mItemsCanFocus && focusResult == null) {
2480                // there was no new view found to take focus, make sure we
2481                // don't leave focus with the old selection
2482                final View focused = getFocusedChild();
2483                if (focused != null) {
2484                    focused.clearFocus();
2485                }
2486            }
2487            needToRedraw = true;
2488            checkSelectionChanged();
2489        }
2490
2491        if (amountToScroll > 0) {
2492            scrollListItemsBy((direction == View.FOCUS_UP) ? amountToScroll : -amountToScroll);
2493            needToRedraw = true;
2494        }
2495
2496        // if we didn't find a new focusable, make sure any existing focused
2497        // item that was panned off screen gives up focus.
2498        if (mItemsCanFocus && (focusResult == null)
2499                && selectedView != null && selectedView.hasFocus()) {
2500            final View focused = selectedView.findFocus();
2501            if (!isViewAncestorOf(focused, this) || distanceToView(focused) > 0) {
2502                focused.clearFocus();
2503            }
2504        }
2505
2506        // if  the current selection is panned off, we need to remove the selection
2507        if (nextSelectedPosition == INVALID_POSITION && selectedView != null
2508                && !isViewAncestorOf(selectedView, this)) {
2509            selectedView = null;
2510            hideSelector();
2511
2512            // but we don't want to set the ressurect position (that would make subsequent
2513            // unhandled key events bring back the item we just scrolled off!)
2514            mResurrectToPosition = INVALID_POSITION;
2515        }
2516
2517        if (needToRedraw) {
2518            if (selectedView != null) {
2519                positionSelector(selectedPos, selectedView);
2520                mSelectedTop = selectedView.getTop();
2521            }
2522            if (!awakenScrollBars()) {
2523                invalidate();
2524            }
2525            invokeOnItemScrollListener();
2526            return true;
2527        }
2528
2529        return false;
2530    }
2531
2532    /**
2533     * When selection changes, it is possible that the previously selected or the
2534     * next selected item will change its size.  If so, we need to offset some folks,
2535     * and re-layout the items as appropriate.
2536     *
2537     * @param selectedView The currently selected view (before changing selection).
2538     *   should be <code>null</code> if there was no previous selection.
2539     * @param direction Either {@link android.view.View#FOCUS_UP} or
2540     *        {@link android.view.View#FOCUS_DOWN}.
2541     * @param newSelectedPosition The position of the next selection.
2542     * @param newFocusAssigned whether new focus was assigned.  This matters because
2543     *        when something has focus, we don't want to show selection (ugh).
2544     */
2545    private void handleNewSelectionChange(View selectedView, int direction, int newSelectedPosition,
2546            boolean newFocusAssigned) {
2547        if (newSelectedPosition == INVALID_POSITION) {
2548            throw new IllegalArgumentException("newSelectedPosition needs to be valid");
2549        }
2550
2551        // whether or not we are moving down or up, we want to preserve the
2552        // top of whatever view is on top:
2553        // - moving down: the view that had selection
2554        // - moving up: the view that is getting selection
2555        View topView;
2556        View bottomView;
2557        int topViewIndex, bottomViewIndex;
2558        boolean topSelected = false;
2559        final int selectedIndex = mSelectedPosition - mFirstPosition;
2560        final int nextSelectedIndex = newSelectedPosition - mFirstPosition;
2561        if (direction == View.FOCUS_UP) {
2562            topViewIndex = nextSelectedIndex;
2563            bottomViewIndex = selectedIndex;
2564            topView = getChildAt(topViewIndex);
2565            bottomView = selectedView;
2566            topSelected = true;
2567        } else {
2568            topViewIndex = selectedIndex;
2569            bottomViewIndex = nextSelectedIndex;
2570            topView = selectedView;
2571            bottomView = getChildAt(bottomViewIndex);
2572        }
2573
2574        final int numChildren = getChildCount();
2575
2576        // start with top view: is it changing size?
2577        if (topView != null) {
2578            topView.setSelected(!newFocusAssigned && topSelected);
2579            measureAndAdjustDown(topView, topViewIndex, numChildren);
2580        }
2581
2582        // is the bottom view changing size?
2583        if (bottomView != null) {
2584            bottomView.setSelected(!newFocusAssigned && !topSelected);
2585            measureAndAdjustDown(bottomView, bottomViewIndex, numChildren);
2586        }
2587    }
2588
2589    /**
2590     * Re-measure a child, and if its height changes, lay it out preserving its
2591     * top, and adjust the children below it appropriately.
2592     * @param child The child
2593     * @param childIndex The view group index of the child.
2594     * @param numChildren The number of children in the view group.
2595     */
2596    private void measureAndAdjustDown(View child, int childIndex, int numChildren) {
2597        int oldHeight = child.getHeight();
2598        measureItem(child);
2599        if (child.getMeasuredHeight() != oldHeight) {
2600            // lay out the view, preserving its top
2601            relayoutMeasuredItem(child);
2602
2603            // adjust views below appropriately
2604            final int heightDelta = child.getMeasuredHeight() - oldHeight;
2605            for (int i = childIndex + 1; i < numChildren; i++) {
2606                getChildAt(i).offsetTopAndBottom(heightDelta);
2607            }
2608        }
2609    }
2610
2611    /**
2612     * Measure a particular list child.
2613     * TODO: unify with setUpChild.
2614     * @param child The child.
2615     */
2616    private void measureItem(View child) {
2617        ViewGroup.LayoutParams p = child.getLayoutParams();
2618        if (p == null) {
2619            p = new ViewGroup.LayoutParams(
2620                    ViewGroup.LayoutParams.MATCH_PARENT,
2621                    ViewGroup.LayoutParams.WRAP_CONTENT);
2622        }
2623
2624        int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
2625                mListPadding.left + mListPadding.right, p.width);
2626        int lpHeight = p.height;
2627        int childHeightSpec;
2628        if (lpHeight > 0) {
2629            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
2630        } else {
2631            childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
2632        }
2633        child.measure(childWidthSpec, childHeightSpec);
2634    }
2635
2636    /**
2637     * Layout a child that has been measured, preserving its top position.
2638     * TODO: unify with setUpChild.
2639     * @param child The child.
2640     */
2641    private void relayoutMeasuredItem(View child) {
2642        final int w = child.getMeasuredWidth();
2643        final int h = child.getMeasuredHeight();
2644        final int childLeft = mListPadding.left;
2645        final int childRight = childLeft + w;
2646        final int childTop = child.getTop();
2647        final int childBottom = childTop + h;
2648        child.layout(childLeft, childTop, childRight, childBottom);
2649    }
2650
2651    /**
2652     * @return The amount to preview next items when arrow srolling.
2653     */
2654    private int getArrowScrollPreviewLength() {
2655        return Math.max(MIN_SCROLL_PREVIEW_PIXELS, getVerticalFadingEdgeLength());
2656    }
2657
2658    /**
2659     * Determine how much we need to scroll in order to get the next selected view
2660     * visible, with a fading edge showing below as applicable.  The amount is
2661     * capped at {@link #getMaxScrollAmount()} .
2662     *
2663     * @param direction either {@link android.view.View#FOCUS_UP} or
2664     *        {@link android.view.View#FOCUS_DOWN}.
2665     * @param nextSelectedPosition The position of the next selection, or
2666     *        {@link #INVALID_POSITION} if there is no next selectable position
2667     * @return The amount to scroll. Note: this is always positive!  Direction
2668     *         needs to be taken into account when actually scrolling.
2669     */
2670    private int amountToScroll(int direction, int nextSelectedPosition) {
2671        final int listBottom = getHeight() - mListPadding.bottom;
2672        final int listTop = mListPadding.top;
2673
2674        int numChildren = getChildCount();
2675
2676        if (direction == View.FOCUS_DOWN) {
2677            int indexToMakeVisible = numChildren - 1;
2678            if (nextSelectedPosition != INVALID_POSITION) {
2679                indexToMakeVisible = nextSelectedPosition - mFirstPosition;
2680            }
2681            while (numChildren <= indexToMakeVisible) {
2682                // Child to view is not attached yet.
2683                addViewBelow(getChildAt(numChildren - 1), mFirstPosition + numChildren - 1);
2684                numChildren++;
2685            }
2686            final int positionToMakeVisible = mFirstPosition + indexToMakeVisible;
2687            final View viewToMakeVisible = getChildAt(indexToMakeVisible);
2688
2689            int goalBottom = listBottom;
2690            if (positionToMakeVisible < mItemCount - 1) {
2691                goalBottom -= getArrowScrollPreviewLength();
2692            }
2693
2694            if (viewToMakeVisible.getBottom() <= goalBottom) {
2695                // item is fully visible.
2696                return 0;
2697            }
2698
2699            if (nextSelectedPosition != INVALID_POSITION
2700                    && (goalBottom - viewToMakeVisible.getTop()) >= getMaxScrollAmount()) {
2701                // item already has enough of it visible, changing selection is good enough
2702                return 0;
2703            }
2704
2705            int amountToScroll = (viewToMakeVisible.getBottom() - goalBottom);
2706
2707            if ((mFirstPosition + numChildren) == mItemCount) {
2708                // last is last in list -> make sure we don't scroll past it
2709                final int max = getChildAt(numChildren - 1).getBottom() - listBottom;
2710                amountToScroll = Math.min(amountToScroll, max);
2711            }
2712
2713            return Math.min(amountToScroll, getMaxScrollAmount());
2714        } else {
2715            int indexToMakeVisible = 0;
2716            if (nextSelectedPosition != INVALID_POSITION) {
2717                indexToMakeVisible = nextSelectedPosition - mFirstPosition;
2718            }
2719            while (indexToMakeVisible < 0) {
2720                // Child to view is not attached yet.
2721                addViewAbove(getChildAt(0), mFirstPosition);
2722                mFirstPosition--;
2723                indexToMakeVisible = nextSelectedPosition - mFirstPosition;
2724            }
2725            final int positionToMakeVisible = mFirstPosition + indexToMakeVisible;
2726            final View viewToMakeVisible = getChildAt(indexToMakeVisible);
2727            int goalTop = listTop;
2728            if (positionToMakeVisible > 0) {
2729                goalTop += getArrowScrollPreviewLength();
2730            }
2731            if (viewToMakeVisible.getTop() >= goalTop) {
2732                // item is fully visible.
2733                return 0;
2734            }
2735
2736            if (nextSelectedPosition != INVALID_POSITION &&
2737                    (viewToMakeVisible.getBottom() - goalTop) >= getMaxScrollAmount()) {
2738                // item already has enough of it visible, changing selection is good enough
2739                return 0;
2740            }
2741
2742            int amountToScroll = (goalTop - viewToMakeVisible.getTop());
2743            if (mFirstPosition == 0) {
2744                // first is first in list -> make sure we don't scroll past it
2745                final int max = listTop - getChildAt(0).getTop();
2746                amountToScroll = Math.min(amountToScroll,  max);
2747            }
2748            return Math.min(amountToScroll, getMaxScrollAmount());
2749        }
2750    }
2751
2752    /**
2753     * Holds results of focus aware arrow scrolling.
2754     */
2755    static private class ArrowScrollFocusResult {
2756        private int mSelectedPosition;
2757        private int mAmountToScroll;
2758
2759        /**
2760         * How {@link android.widget.ListView#arrowScrollFocused} returns its values.
2761         */
2762        void populate(int selectedPosition, int amountToScroll) {
2763            mSelectedPosition = selectedPosition;
2764            mAmountToScroll = amountToScroll;
2765        }
2766
2767        public int getSelectedPosition() {
2768            return mSelectedPosition;
2769        }
2770
2771        public int getAmountToScroll() {
2772            return mAmountToScroll;
2773        }
2774    }
2775
2776    /**
2777     * @param direction either {@link android.view.View#FOCUS_UP} or
2778     *        {@link android.view.View#FOCUS_DOWN}.
2779     * @return The position of the next selectable position of the views that
2780     *         are currently visible, taking into account the fact that there might
2781     *         be no selection.  Returns {@link #INVALID_POSITION} if there is no
2782     *         selectable view on screen in the given direction.
2783     */
2784    private int lookForSelectablePositionOnScreen(int direction) {
2785        final int firstPosition = mFirstPosition;
2786        if (direction == View.FOCUS_DOWN) {
2787            int startPos = (mSelectedPosition != INVALID_POSITION) ?
2788                    mSelectedPosition + 1 :
2789                    firstPosition;
2790            if (startPos >= mAdapter.getCount()) {
2791                return INVALID_POSITION;
2792            }
2793            if (startPos < firstPosition) {
2794                startPos = firstPosition;
2795            }
2796
2797            final int lastVisiblePos = getLastVisiblePosition();
2798            final ListAdapter adapter = getAdapter();
2799            for (int pos = startPos; pos <= lastVisiblePos; pos++) {
2800                if (adapter.isEnabled(pos)
2801                        && getChildAt(pos - firstPosition).getVisibility() == View.VISIBLE) {
2802                    return pos;
2803                }
2804            }
2805        } else {
2806            int last = firstPosition + getChildCount() - 1;
2807            int startPos = (mSelectedPosition != INVALID_POSITION) ?
2808                    mSelectedPosition - 1 :
2809                    firstPosition + getChildCount() - 1;
2810            if (startPos < 0 || startPos >= mAdapter.getCount()) {
2811                return INVALID_POSITION;
2812            }
2813            if (startPos > last) {
2814                startPos = last;
2815            }
2816
2817            final ListAdapter adapter = getAdapter();
2818            for (int pos = startPos; pos >= firstPosition; pos--) {
2819                if (adapter.isEnabled(pos)
2820                        && getChildAt(pos - firstPosition).getVisibility() == View.VISIBLE) {
2821                    return pos;
2822                }
2823            }
2824        }
2825        return INVALID_POSITION;
2826    }
2827
2828    /**
2829     * Do an arrow scroll based on focus searching.  If a new view is
2830     * given focus, return the selection delta and amount to scroll via
2831     * an {@link ArrowScrollFocusResult}, otherwise, return null.
2832     *
2833     * @param direction either {@link android.view.View#FOCUS_UP} or
2834     *        {@link android.view.View#FOCUS_DOWN}.
2835     * @return The result if focus has changed, or <code>null</code>.
2836     */
2837    private ArrowScrollFocusResult arrowScrollFocused(final int direction) {
2838        final View selectedView = getSelectedView();
2839        View newFocus;
2840        if (selectedView != null && selectedView.hasFocus()) {
2841            View oldFocus = selectedView.findFocus();
2842            newFocus = FocusFinder.getInstance().findNextFocus(this, oldFocus, direction);
2843        } else {
2844            if (direction == View.FOCUS_DOWN) {
2845                final boolean topFadingEdgeShowing = (mFirstPosition > 0);
2846                final int listTop = mListPadding.top +
2847                        (topFadingEdgeShowing ? getArrowScrollPreviewLength() : 0);
2848                final int ySearchPoint =
2849                        (selectedView != null && selectedView.getTop() > listTop) ?
2850                                selectedView.getTop() :
2851                                listTop;
2852                mTempRect.set(0, ySearchPoint, 0, ySearchPoint);
2853            } else {
2854                final boolean bottomFadingEdgeShowing =
2855                        (mFirstPosition + getChildCount() - 1) < mItemCount;
2856                final int listBottom = getHeight() - mListPadding.bottom -
2857                        (bottomFadingEdgeShowing ? getArrowScrollPreviewLength() : 0);
2858                final int ySearchPoint =
2859                        (selectedView != null && selectedView.getBottom() < listBottom) ?
2860                                selectedView.getBottom() :
2861                                listBottom;
2862                mTempRect.set(0, ySearchPoint, 0, ySearchPoint);
2863            }
2864            newFocus = FocusFinder.getInstance().findNextFocusFromRect(this, mTempRect, direction);
2865        }
2866
2867        if (newFocus != null) {
2868            final int positionOfNewFocus = positionOfNewFocus(newFocus);
2869
2870            // if the focus change is in a different new position, make sure
2871            // we aren't jumping over another selectable position
2872            if (mSelectedPosition != INVALID_POSITION && positionOfNewFocus != mSelectedPosition) {
2873                final int selectablePosition = lookForSelectablePositionOnScreen(direction);
2874                if (selectablePosition != INVALID_POSITION &&
2875                        ((direction == View.FOCUS_DOWN && selectablePosition < positionOfNewFocus) ||
2876                        (direction == View.FOCUS_UP && selectablePosition > positionOfNewFocus))) {
2877                    return null;
2878                }
2879            }
2880
2881            int focusScroll = amountToScrollToNewFocus(direction, newFocus, positionOfNewFocus);
2882
2883            final int maxScrollAmount = getMaxScrollAmount();
2884            if (focusScroll < maxScrollAmount) {
2885                // not moving too far, safe to give next view focus
2886                newFocus.requestFocus(direction);
2887                mArrowScrollFocusResult.populate(positionOfNewFocus, focusScroll);
2888                return mArrowScrollFocusResult;
2889            } else if (distanceToView(newFocus) < maxScrollAmount){
2890                // Case to consider:
2891                // too far to get entire next focusable on screen, but by going
2892                // max scroll amount, we are getting it at least partially in view,
2893                // so give it focus and scroll the max ammount.
2894                newFocus.requestFocus(direction);
2895                mArrowScrollFocusResult.populate(positionOfNewFocus, maxScrollAmount);
2896                return mArrowScrollFocusResult;
2897            }
2898        }
2899        return null;
2900    }
2901
2902    /**
2903     * @param newFocus The view that would have focus.
2904     * @return the position that contains newFocus
2905     */
2906    private int positionOfNewFocus(View newFocus) {
2907        final int numChildren = getChildCount();
2908        for (int i = 0; i < numChildren; i++) {
2909            final View child = getChildAt(i);
2910            if (isViewAncestorOf(newFocus, child)) {
2911                return mFirstPosition + i;
2912            }
2913        }
2914        throw new IllegalArgumentException("newFocus is not a child of any of the"
2915                + " children of the list!");
2916    }
2917
2918    /**
2919     * Return true if child is an ancestor of parent, (or equal to the parent).
2920     */
2921    private boolean isViewAncestorOf(View child, View parent) {
2922        if (child == parent) {
2923            return true;
2924        }
2925
2926        final ViewParent theParent = child.getParent();
2927        return (theParent instanceof ViewGroup) && isViewAncestorOf((View) theParent, parent);
2928    }
2929
2930    /**
2931     * Determine how much we need to scroll in order to get newFocus in view.
2932     * @param direction either {@link android.view.View#FOCUS_UP} or
2933     *        {@link android.view.View#FOCUS_DOWN}.
2934     * @param newFocus The view that would take focus.
2935     * @param positionOfNewFocus The position of the list item containing newFocus
2936     * @return The amount to scroll.  Note: this is always positive!  Direction
2937     *   needs to be taken into account when actually scrolling.
2938     */
2939    private int amountToScrollToNewFocus(int direction, View newFocus, int positionOfNewFocus) {
2940        int amountToScroll = 0;
2941        newFocus.getDrawingRect(mTempRect);
2942        offsetDescendantRectToMyCoords(newFocus, mTempRect);
2943        if (direction == View.FOCUS_UP) {
2944            if (mTempRect.top < mListPadding.top) {
2945                amountToScroll = mListPadding.top - mTempRect.top;
2946                if (positionOfNewFocus > 0) {
2947                    amountToScroll += getArrowScrollPreviewLength();
2948                }
2949            }
2950        } else {
2951            final int listBottom = getHeight() - mListPadding.bottom;
2952            if (mTempRect.bottom > listBottom) {
2953                amountToScroll = mTempRect.bottom - listBottom;
2954                if (positionOfNewFocus < mItemCount - 1) {
2955                    amountToScroll += getArrowScrollPreviewLength();
2956                }
2957            }
2958        }
2959        return amountToScroll;
2960    }
2961
2962    /**
2963     * Determine the distance to the nearest edge of a view in a particular
2964     * direction.
2965     *
2966     * @param descendant A descendant of this list.
2967     * @return The distance, or 0 if the nearest edge is already on screen.
2968     */
2969    private int distanceToView(View descendant) {
2970        int distance = 0;
2971        descendant.getDrawingRect(mTempRect);
2972        offsetDescendantRectToMyCoords(descendant, mTempRect);
2973        final int listBottom = mBottom - mTop - mListPadding.bottom;
2974        if (mTempRect.bottom < mListPadding.top) {
2975            distance = mListPadding.top - mTempRect.bottom;
2976        } else if (mTempRect.top > listBottom) {
2977            distance = mTempRect.top - listBottom;
2978        }
2979        return distance;
2980    }
2981
2982
2983    /**
2984     * Scroll the children by amount, adding a view at the end and removing
2985     * views that fall off as necessary.
2986     *
2987     * @param amount The amount (positive or negative) to scroll.
2988     */
2989    private void scrollListItemsBy(int amount) {
2990        offsetChildrenTopAndBottom(amount);
2991
2992        final int listBottom = getHeight() - mListPadding.bottom;
2993        final int listTop = mListPadding.top;
2994        final AbsListView.RecycleBin recycleBin = mRecycler;
2995
2996        if (amount < 0) {
2997            // shifted items up
2998
2999            // may need to pan views into the bottom space
3000            int numChildren = getChildCount();
3001            View last = getChildAt(numChildren - 1);
3002            while (last.getBottom() < listBottom) {
3003                final int lastVisiblePosition = mFirstPosition + numChildren - 1;
3004                if (lastVisiblePosition < mItemCount - 1) {
3005                    last = addViewBelow(last, lastVisiblePosition);
3006                    numChildren++;
3007                } else {
3008                    break;
3009                }
3010            }
3011
3012            // may have brought in the last child of the list that is skinnier
3013            // than the fading edge, thereby leaving space at the end.  need
3014            // to shift back
3015            if (last.getBottom() < listBottom) {
3016                offsetChildrenTopAndBottom(listBottom - last.getBottom());
3017            }
3018
3019            // top views may be panned off screen
3020            View first = getChildAt(0);
3021            while (first.getBottom() < listTop) {
3022                AbsListView.LayoutParams layoutParams = (LayoutParams) first.getLayoutParams();
3023                if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) {
3024                    recycleBin.addScrapView(first, mFirstPosition);
3025                }
3026                detachViewFromParent(first);
3027                first = getChildAt(0);
3028                mFirstPosition++;
3029            }
3030        } else {
3031            // shifted items down
3032            View first = getChildAt(0);
3033
3034            // may need to pan views into top
3035            while ((first.getTop() > listTop) && (mFirstPosition > 0)) {
3036                first = addViewAbove(first, mFirstPosition);
3037                mFirstPosition--;
3038            }
3039
3040            // may have brought the very first child of the list in too far and
3041            // need to shift it back
3042            if (first.getTop() > listTop) {
3043                offsetChildrenTopAndBottom(listTop - first.getTop());
3044            }
3045
3046            int lastIndex = getChildCount() - 1;
3047            View last = getChildAt(lastIndex);
3048
3049            // bottom view may be panned off screen
3050            while (last.getTop() > listBottom) {
3051                AbsListView.LayoutParams layoutParams = (LayoutParams) last.getLayoutParams();
3052                if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) {
3053                    recycleBin.addScrapView(last, mFirstPosition+lastIndex);
3054                }
3055                detachViewFromParent(last);
3056                last = getChildAt(--lastIndex);
3057            }
3058        }
3059    }
3060
3061    private View addViewAbove(View theView, int position) {
3062        int abovePosition = position - 1;
3063        View view = obtainView(abovePosition, mIsScrap);
3064        int edgeOfNewChild = theView.getTop() - mDividerHeight;
3065        setupChild(view, abovePosition, edgeOfNewChild, false, mListPadding.left,
3066                false, mIsScrap[0]);
3067        return view;
3068    }
3069
3070    private View addViewBelow(View theView, int position) {
3071        int belowPosition = position + 1;
3072        View view = obtainView(belowPosition, mIsScrap);
3073        int edgeOfNewChild = theView.getBottom() + mDividerHeight;
3074        setupChild(view, belowPosition, edgeOfNewChild, true, mListPadding.left,
3075                false, mIsScrap[0]);
3076        return view;
3077    }
3078
3079    /**
3080     * Indicates that the views created by the ListAdapter can contain focusable
3081     * items.
3082     *
3083     * @param itemsCanFocus true if items can get focus, false otherwise
3084     */
3085    public void setItemsCanFocus(boolean itemsCanFocus) {
3086        mItemsCanFocus = itemsCanFocus;
3087        if (!itemsCanFocus) {
3088            setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
3089        }
3090    }
3091
3092    /**
3093     * @return Whether the views created by the ListAdapter can contain focusable
3094     * items.
3095     */
3096    public boolean getItemsCanFocus() {
3097        return mItemsCanFocus;
3098    }
3099
3100    @Override
3101    public boolean isOpaque() {
3102        boolean retValue = (mCachingActive && mIsCacheColorOpaque && mDividerIsOpaque &&
3103                hasOpaqueScrollbars()) || super.isOpaque();
3104        if (retValue) {
3105            // only return true if the list items cover the entire area of the view
3106            final int listTop = mListPadding != null ? mListPadding.top : mPaddingTop;
3107            View first = getChildAt(0);
3108            if (first == null || first.getTop() > listTop) {
3109                return false;
3110            }
3111            final int listBottom = getHeight() -
3112                    (mListPadding != null ? mListPadding.bottom : mPaddingBottom);
3113            View last = getChildAt(getChildCount() - 1);
3114            if (last == null || last.getBottom() < listBottom) {
3115                return false;
3116            }
3117        }
3118        return retValue;
3119    }
3120
3121    @Override
3122    public void setCacheColorHint(int color) {
3123        final boolean opaque = (color >>> 24) == 0xFF;
3124        mIsCacheColorOpaque = opaque;
3125        if (opaque) {
3126            if (mDividerPaint == null) {
3127                mDividerPaint = new Paint();
3128            }
3129            mDividerPaint.setColor(color);
3130        }
3131        super.setCacheColorHint(color);
3132    }
3133
3134    void drawOverscrollHeader(Canvas canvas, Drawable drawable, Rect bounds) {
3135        final int height = drawable.getMinimumHeight();
3136
3137        canvas.save();
3138        canvas.clipRect(bounds);
3139
3140        final int span = bounds.bottom - bounds.top;
3141        if (span < height) {
3142            bounds.top = bounds.bottom - height;
3143        }
3144
3145        drawable.setBounds(bounds);
3146        drawable.draw(canvas);
3147
3148        canvas.restore();
3149    }
3150
3151    void drawOverscrollFooter(Canvas canvas, Drawable drawable, Rect bounds) {
3152        final int height = drawable.getMinimumHeight();
3153
3154        canvas.save();
3155        canvas.clipRect(bounds);
3156
3157        final int span = bounds.bottom - bounds.top;
3158        if (span < height) {
3159            bounds.bottom = bounds.top + height;
3160        }
3161
3162        drawable.setBounds(bounds);
3163        drawable.draw(canvas);
3164
3165        canvas.restore();
3166    }
3167
3168    @Override
3169    protected void dispatchDraw(Canvas canvas) {
3170        if (mCachingStarted) {
3171            mCachingActive = true;
3172        }
3173
3174        // Draw the dividers
3175        final int dividerHeight = mDividerHeight;
3176        final Drawable overscrollHeader = mOverScrollHeader;
3177        final Drawable overscrollFooter = mOverScrollFooter;
3178        final boolean drawOverscrollHeader = overscrollHeader != null;
3179        final boolean drawOverscrollFooter = overscrollFooter != null;
3180        final boolean drawDividers = dividerHeight > 0 && mDivider != null;
3181
3182        if (drawDividers || drawOverscrollHeader || drawOverscrollFooter) {
3183            // Only modify the top and bottom in the loop, we set the left and right here
3184            final Rect bounds = mTempRect;
3185            bounds.left = mPaddingLeft;
3186            bounds.right = mRight - mLeft - mPaddingRight;
3187
3188            final int count = getChildCount();
3189            final int headerCount = mHeaderViewInfos.size();
3190            final int itemCount = mItemCount;
3191            final int footerLimit = (itemCount - mFooterViewInfos.size());
3192            final boolean headerDividers = mHeaderDividersEnabled;
3193            final boolean footerDividers = mFooterDividersEnabled;
3194            final int first = mFirstPosition;
3195            final boolean areAllItemsSelectable = mAreAllItemsSelectable;
3196            final ListAdapter adapter = mAdapter;
3197            // If the list is opaque *and* the background is not, we want to
3198            // fill a rect where the dividers would be for non-selectable items
3199            // If the list is opaque and the background is also opaque, we don't
3200            // need to draw anything since the background will do it for us
3201            final boolean fillForMissingDividers = isOpaque() && !super.isOpaque();
3202
3203            if (fillForMissingDividers && mDividerPaint == null && mIsCacheColorOpaque) {
3204                mDividerPaint = new Paint();
3205                mDividerPaint.setColor(getCacheColorHint());
3206            }
3207            final Paint paint = mDividerPaint;
3208
3209            int effectivePaddingTop = 0;
3210            int effectivePaddingBottom = 0;
3211            if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) {
3212                effectivePaddingTop = mListPadding.top;
3213                effectivePaddingBottom = mListPadding.bottom;
3214            }
3215
3216            final int listBottom = mBottom - mTop - effectivePaddingBottom + mScrollY;
3217            if (!mStackFromBottom) {
3218                int bottom = 0;
3219
3220                // Draw top divider or header for overscroll
3221                final int scrollY = mScrollY;
3222                if (count > 0 && scrollY < 0) {
3223                    if (drawOverscrollHeader) {
3224                        bounds.bottom = 0;
3225                        bounds.top = scrollY;
3226                        drawOverscrollHeader(canvas, overscrollHeader, bounds);
3227                    } else if (drawDividers) {
3228                        bounds.bottom = 0;
3229                        bounds.top = -dividerHeight;
3230                        drawDivider(canvas, bounds, -1);
3231                    }
3232                }
3233
3234                for (int i = 0; i < count; i++) {
3235                    final int itemIndex = (first + i);
3236                    final boolean isHeader = (itemIndex < headerCount);
3237                    final boolean isFooter = (itemIndex >= footerLimit);
3238                    if ((headerDividers || !isHeader) && (footerDividers || !isFooter)) {
3239                        final View child = getChildAt(i);
3240                        bottom = child.getBottom();
3241                        final boolean isLastItem = (i == (count - 1));
3242
3243                        if (drawDividers && (bottom < listBottom)
3244                                && !(drawOverscrollFooter && isLastItem)) {
3245                            final int nextIndex = (itemIndex + 1);
3246                            // Draw dividers between enabled items, headers
3247                            // and/or footers when enabled and requested, and
3248                            // after the last enabled item.
3249                            if (adapter.isEnabled(itemIndex) && (headerDividers || !isHeader
3250                                    && (nextIndex >= headerCount)) && (isLastItem
3251                                    || adapter.isEnabled(nextIndex) && (footerDividers || !isFooter
3252                                            && (nextIndex < footerLimit)))) {
3253                                bounds.top = bottom;
3254                                bounds.bottom = bottom + dividerHeight;
3255                                drawDivider(canvas, bounds, i);
3256                            } else if (fillForMissingDividers) {
3257                                bounds.top = bottom;
3258                                bounds.bottom = bottom + dividerHeight;
3259                                canvas.drawRect(bounds, paint);
3260                            }
3261                        }
3262                    }
3263                }
3264
3265                final int overFooterBottom = mBottom + mScrollY;
3266                if (drawOverscrollFooter && first + count == itemCount &&
3267                        overFooterBottom > bottom) {
3268                    bounds.top = bottom;
3269                    bounds.bottom = overFooterBottom;
3270                    drawOverscrollFooter(canvas, overscrollFooter, bounds);
3271                }
3272            } else {
3273                int top;
3274
3275                final int scrollY = mScrollY;
3276
3277                if (count > 0 && drawOverscrollHeader) {
3278                    bounds.top = scrollY;
3279                    bounds.bottom = getChildAt(0).getTop();
3280                    drawOverscrollHeader(canvas, overscrollHeader, bounds);
3281                }
3282
3283                final int start = drawOverscrollHeader ? 1 : 0;
3284                for (int i = start; i < count; i++) {
3285                    final int itemIndex = (first + i);
3286                    final boolean isHeader = (itemIndex < headerCount);
3287                    final boolean isFooter = (itemIndex >= footerLimit);
3288                    if ((headerDividers || !isHeader) && (footerDividers || !isFooter)) {
3289                        final View child = getChildAt(i);
3290                        top = child.getTop();
3291                        if (drawDividers && (top > effectivePaddingTop)) {
3292                            final boolean isFirstItem = (i == start);
3293                            final int previousIndex = (itemIndex - 1);
3294                            // Draw dividers between enabled items, headers
3295                            // and/or footers when enabled and requested, and
3296                            // before the first enabled item.
3297                            if (adapter.isEnabled(itemIndex) && (headerDividers || !isHeader
3298                                    && (previousIndex >= headerCount)) && (isFirstItem ||
3299                                    adapter.isEnabled(previousIndex) && (footerDividers || !isFooter
3300                                            && (previousIndex < footerLimit)))) {
3301                                bounds.top = top - dividerHeight;
3302                                bounds.bottom = top;
3303                                // Give the method the child ABOVE the divider,
3304                                // so we subtract one from our child position.
3305                                // Give -1 when there is no child above the
3306                                // divider.
3307                                drawDivider(canvas, bounds, i - 1);
3308                            } else if (fillForMissingDividers) {
3309                                bounds.top = top - dividerHeight;
3310                                bounds.bottom = top;
3311                                canvas.drawRect(bounds, paint);
3312                            }
3313                        }
3314                    }
3315                }
3316
3317                if (count > 0 && scrollY > 0) {
3318                    if (drawOverscrollFooter) {
3319                        final int absListBottom = mBottom;
3320                        bounds.top = absListBottom;
3321                        bounds.bottom = absListBottom + scrollY;
3322                        drawOverscrollFooter(canvas, overscrollFooter, bounds);
3323                    } else if (drawDividers) {
3324                        bounds.top = listBottom;
3325                        bounds.bottom = listBottom + dividerHeight;
3326                        drawDivider(canvas, bounds, -1);
3327                    }
3328                }
3329            }
3330        }
3331
3332        // Draw the indicators (these should be drawn above the dividers) and children
3333        super.dispatchDraw(canvas);
3334    }
3335
3336    @Override
3337    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
3338        boolean more = super.drawChild(canvas, child, drawingTime);
3339        if (mCachingActive && child.mCachingFailed) {
3340            mCachingActive = false;
3341        }
3342        return more;
3343    }
3344
3345    /**
3346     * Draws a divider for the given child in the given bounds.
3347     *
3348     * @param canvas The canvas to draw to.
3349     * @param bounds The bounds of the divider.
3350     * @param childIndex The index of child (of the View) above the divider.
3351     *            This will be -1 if there is no child above the divider to be
3352     *            drawn.
3353     */
3354    void drawDivider(Canvas canvas, Rect bounds, int childIndex) {
3355        // This widget draws the same divider for all children
3356        final Drawable divider = mDivider;
3357
3358        divider.setBounds(bounds);
3359        divider.draw(canvas);
3360    }
3361
3362    /**
3363     * Returns the drawable that will be drawn between each item in the list.
3364     *
3365     * @return the current drawable drawn between list elements
3366     */
3367    public Drawable getDivider() {
3368        return mDivider;
3369    }
3370
3371    /**
3372     * Sets the drawable that will be drawn between each item in the list. If the drawable does
3373     * not have an intrinsic height, you should also call {@link #setDividerHeight(int)}
3374     *
3375     * @param divider The drawable to use.
3376     */
3377    public void setDivider(Drawable divider) {
3378        if (divider != null) {
3379            mDividerHeight = divider.getIntrinsicHeight();
3380        } else {
3381            mDividerHeight = 0;
3382        }
3383        mDivider = divider;
3384        mDividerIsOpaque = divider == null || divider.getOpacity() == PixelFormat.OPAQUE;
3385        requestLayout();
3386        invalidate();
3387    }
3388
3389    /**
3390     * @return Returns the height of the divider that will be drawn between each item in the list.
3391     */
3392    public int getDividerHeight() {
3393        return mDividerHeight;
3394    }
3395
3396    /**
3397     * Sets the height of the divider that will be drawn between each item in the list. Calling
3398     * this will override the intrinsic height as set by {@link #setDivider(Drawable)}
3399     *
3400     * @param height The new height of the divider in pixels.
3401     */
3402    public void setDividerHeight(int height) {
3403        mDividerHeight = height;
3404        requestLayout();
3405        invalidate();
3406    }
3407
3408    /**
3409     * Enables or disables the drawing of the divider for header views.
3410     *
3411     * @param headerDividersEnabled True to draw the headers, false otherwise.
3412     *
3413     * @see #setFooterDividersEnabled(boolean)
3414     * @see #areHeaderDividersEnabled()
3415     * @see #addHeaderView(android.view.View)
3416     */
3417    public void setHeaderDividersEnabled(boolean headerDividersEnabled) {
3418        mHeaderDividersEnabled = headerDividersEnabled;
3419        invalidate();
3420    }
3421
3422    /**
3423     * @return Whether the drawing of the divider for header views is enabled
3424     *
3425     * @see #setHeaderDividersEnabled(boolean)
3426     */
3427    public boolean areHeaderDividersEnabled() {
3428        return mHeaderDividersEnabled;
3429    }
3430
3431    /**
3432     * Enables or disables the drawing of the divider for footer views.
3433     *
3434     * @param footerDividersEnabled True to draw the footers, false otherwise.
3435     *
3436     * @see #setHeaderDividersEnabled(boolean)
3437     * @see #areFooterDividersEnabled()
3438     * @see #addFooterView(android.view.View)
3439     */
3440    public void setFooterDividersEnabled(boolean footerDividersEnabled) {
3441        mFooterDividersEnabled = footerDividersEnabled;
3442        invalidate();
3443    }
3444
3445    /**
3446     * @return Whether the drawing of the divider for footer views is enabled
3447     *
3448     * @see #setFooterDividersEnabled(boolean)
3449     */
3450    public boolean areFooterDividersEnabled() {
3451        return mFooterDividersEnabled;
3452    }
3453
3454    /**
3455     * Sets the drawable that will be drawn above all other list content.
3456     * This area can become visible when the user overscrolls the list.
3457     *
3458     * @param header The drawable to use
3459     */
3460    public void setOverscrollHeader(Drawable header) {
3461        mOverScrollHeader = header;
3462        if (mScrollY < 0) {
3463            invalidate();
3464        }
3465    }
3466
3467    /**
3468     * @return The drawable that will be drawn above all other list content
3469     */
3470    public Drawable getOverscrollHeader() {
3471        return mOverScrollHeader;
3472    }
3473
3474    /**
3475     * Sets the drawable that will be drawn below all other list content.
3476     * This area can become visible when the user overscrolls the list,
3477     * or when the list's content does not fully fill the container area.
3478     *
3479     * @param footer The drawable to use
3480     */
3481    public void setOverscrollFooter(Drawable footer) {
3482        mOverScrollFooter = footer;
3483        invalidate();
3484    }
3485
3486    /**
3487     * @return The drawable that will be drawn below all other list content
3488     */
3489    public Drawable getOverscrollFooter() {
3490        return mOverScrollFooter;
3491    }
3492
3493    @Override
3494    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3495        super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
3496
3497        final ListAdapter adapter = mAdapter;
3498        int closetChildIndex = -1;
3499        int closestChildTop = 0;
3500        if (adapter != null && gainFocus && previouslyFocusedRect != null) {
3501            previouslyFocusedRect.offset(mScrollX, mScrollY);
3502
3503            // Don't cache the result of getChildCount or mFirstPosition here,
3504            // it could change in layoutChildren.
3505            if (adapter.getCount() < getChildCount() + mFirstPosition) {
3506                mLayoutMode = LAYOUT_NORMAL;
3507                layoutChildren();
3508            }
3509
3510            // figure out which item should be selected based on previously
3511            // focused rect
3512            Rect otherRect = mTempRect;
3513            int minDistance = Integer.MAX_VALUE;
3514            final int childCount = getChildCount();
3515            final int firstPosition = mFirstPosition;
3516
3517            for (int i = 0; i < childCount; i++) {
3518                // only consider selectable views
3519                if (!adapter.isEnabled(firstPosition + i)) {
3520                    continue;
3521                }
3522
3523                View other = getChildAt(i);
3524                other.getDrawingRect(otherRect);
3525                offsetDescendantRectToMyCoords(other, otherRect);
3526                int distance = getDistance(previouslyFocusedRect, otherRect, direction);
3527
3528                if (distance < minDistance) {
3529                    minDistance = distance;
3530                    closetChildIndex = i;
3531                    closestChildTop = other.getTop();
3532                }
3533            }
3534        }
3535
3536        if (closetChildIndex >= 0) {
3537            setSelectionFromTop(closetChildIndex + mFirstPosition, closestChildTop);
3538        } else {
3539            requestLayout();
3540        }
3541    }
3542
3543
3544    /*
3545     * (non-Javadoc)
3546     *
3547     * Children specified in XML are assumed to be header views. After we have
3548     * parsed them move them out of the children list and into mHeaderViews.
3549     */
3550    @Override
3551    protected void onFinishInflate() {
3552        super.onFinishInflate();
3553
3554        int count = getChildCount();
3555        if (count > 0) {
3556            for (int i = 0; i < count; ++i) {
3557                addHeaderView(getChildAt(i));
3558            }
3559            removeAllViews();
3560        }
3561    }
3562
3563    /* (non-Javadoc)
3564     * @see android.view.View#findViewById(int)
3565     * First look in our children, then in any header and footer views that may be scrolled off.
3566     */
3567    @Override
3568    protected View findViewTraversal(int id) {
3569        View v;
3570        v = super.findViewTraversal(id);
3571        if (v == null) {
3572            v = findViewInHeadersOrFooters(mHeaderViewInfos, id);
3573            if (v != null) {
3574                return v;
3575            }
3576            v = findViewInHeadersOrFooters(mFooterViewInfos, id);
3577            if (v != null) {
3578                return v;
3579            }
3580        }
3581        return v;
3582    }
3583
3584    /* (non-Javadoc)
3585     *
3586     * Look in the passed in list of headers or footers for the view.
3587     */
3588    View findViewInHeadersOrFooters(ArrayList<FixedViewInfo> where, int id) {
3589        if (where != null) {
3590            int len = where.size();
3591            View v;
3592
3593            for (int i = 0; i < len; i++) {
3594                v = where.get(i).view;
3595
3596                if (!v.isRootNamespace()) {
3597                    v = v.findViewById(id);
3598
3599                    if (v != null) {
3600                        return v;
3601                    }
3602                }
3603            }
3604        }
3605        return null;
3606    }
3607
3608    /* (non-Javadoc)
3609     * @see android.view.View#findViewWithTag(Object)
3610     * First look in our children, then in any header and footer views that may be scrolled off.
3611     */
3612    @Override
3613    protected View findViewWithTagTraversal(Object tag) {
3614        View v;
3615        v = super.findViewWithTagTraversal(tag);
3616        if (v == null) {
3617            v = findViewWithTagInHeadersOrFooters(mHeaderViewInfos, tag);
3618            if (v != null) {
3619                return v;
3620            }
3621
3622            v = findViewWithTagInHeadersOrFooters(mFooterViewInfos, tag);
3623            if (v != null) {
3624                return v;
3625            }
3626        }
3627        return v;
3628    }
3629
3630    /* (non-Javadoc)
3631     *
3632     * Look in the passed in list of headers or footers for the view with the tag.
3633     */
3634    View findViewWithTagInHeadersOrFooters(ArrayList<FixedViewInfo> where, Object tag) {
3635        if (where != null) {
3636            int len = where.size();
3637            View v;
3638
3639            for (int i = 0; i < len; i++) {
3640                v = where.get(i).view;
3641
3642                if (!v.isRootNamespace()) {
3643                    v = v.findViewWithTag(tag);
3644
3645                    if (v != null) {
3646                        return v;
3647                    }
3648                }
3649            }
3650        }
3651        return null;
3652    }
3653
3654    /**
3655     * @hide
3656     * @see android.view.View#findViewByPredicate(Predicate)
3657     * First look in our children, then in any header and footer views that may be scrolled off.
3658     */
3659    @Override
3660    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
3661        View v;
3662        v = super.findViewByPredicateTraversal(predicate, childToSkip);
3663        if (v == null) {
3664            v = findViewByPredicateInHeadersOrFooters(mHeaderViewInfos, predicate, childToSkip);
3665            if (v != null) {
3666                return v;
3667            }
3668
3669            v = findViewByPredicateInHeadersOrFooters(mFooterViewInfos, predicate, childToSkip);
3670            if (v != null) {
3671                return v;
3672            }
3673        }
3674        return v;
3675    }
3676
3677    /* (non-Javadoc)
3678     *
3679     * Look in the passed in list of headers or footers for the first view that matches
3680     * the predicate.
3681     */
3682    View findViewByPredicateInHeadersOrFooters(ArrayList<FixedViewInfo> where,
3683            Predicate<View> predicate, View childToSkip) {
3684        if (where != null) {
3685            int len = where.size();
3686            View v;
3687
3688            for (int i = 0; i < len; i++) {
3689                v = where.get(i).view;
3690
3691                if (v != childToSkip && !v.isRootNamespace()) {
3692                    v = v.findViewByPredicate(predicate);
3693
3694                    if (v != null) {
3695                        return v;
3696                    }
3697                }
3698            }
3699        }
3700        return null;
3701    }
3702
3703    /**
3704     * Returns the set of checked items ids. The result is only valid if the
3705     * choice mode has not been set to {@link #CHOICE_MODE_NONE}.
3706     *
3707     * @return A new array which contains the id of each checked item in the
3708     *         list.
3709     *
3710     * @deprecated Use {@link #getCheckedItemIds()} instead.
3711     */
3712    @Deprecated
3713    public long[] getCheckItemIds() {
3714        // Use new behavior that correctly handles stable ID mapping.
3715        if (mAdapter != null && mAdapter.hasStableIds()) {
3716            return getCheckedItemIds();
3717        }
3718
3719        // Old behavior was buggy, but would sort of work for adapters without stable IDs.
3720        // Fall back to it to support legacy apps.
3721        if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null && mAdapter != null) {
3722            final SparseBooleanArray states = mCheckStates;
3723            final int count = states.size();
3724            final long[] ids = new long[count];
3725            final ListAdapter adapter = mAdapter;
3726
3727            int checkedCount = 0;
3728            for (int i = 0; i < count; i++) {
3729                if (states.valueAt(i)) {
3730                    ids[checkedCount++] = adapter.getItemId(states.keyAt(i));
3731                }
3732            }
3733
3734            // Trim array if needed. mCheckStates may contain false values
3735            // resulting in checkedCount being smaller than count.
3736            if (checkedCount == count) {
3737                return ids;
3738            } else {
3739                final long[] result = new long[checkedCount];
3740                System.arraycopy(ids, 0, result, 0, checkedCount);
3741
3742                return result;
3743            }
3744        }
3745        return new long[0];
3746    }
3747
3748    @Override
3749    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
3750        super.onInitializeAccessibilityEvent(event);
3751        event.setClassName(ListView.class.getName());
3752    }
3753
3754    @Override
3755    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
3756        super.onInitializeAccessibilityNodeInfo(info);
3757        info.setClassName(ListView.class.getName());
3758
3759        final int count = getCount();
3760        final CollectionInfo collectionInfo = CollectionInfo.obtain(1, count, false);
3761        info.setCollectionInfo(collectionInfo);
3762    }
3763
3764    @Override
3765    public void onInitializeAccessibilityNodeInfoForItem(
3766            View view, int position, AccessibilityNodeInfo info) {
3767        super.onInitializeAccessibilityNodeInfoForItem(view, position, info);
3768
3769        final LayoutParams lp = (LayoutParams) view.getLayoutParams();
3770        final boolean isHeading = lp != null && lp.viewType != ITEM_VIEW_TYPE_HEADER_OR_FOOTER;
3771        final CollectionItemInfo itemInfo = CollectionItemInfo.obtain(0, 1, position, 1, isHeading);
3772        info.setCollectionItemInfo(itemInfo);
3773    }
3774}
3775