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