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