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