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