ListView.java revision 1ad11b9c6c7b555c27b917f26ecc08446f589284
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     * Handle an arrow scroll going up or down.  Take into account whether items are selectable,
2421     * whether there are focusable items etc.
2422     *
2423     * @param direction Either {@link android.view.View#FOCUS_UP} or {@link android.view.View#FOCUS_DOWN}.
2424     * @return Whether any scrolling, selection or focus change occured.
2425     */
2426    private boolean arrowScrollImpl(int direction) {
2427        if (getChildCount() <= 0) {
2428            return false;
2429        }
2430
2431        View selectedView = getSelectedView();
2432        int selectedPos = mSelectedPosition;
2433
2434        int nextSelectedPosition = (direction == View.FOCUS_DOWN) ?
2435                lookForSelectablePosition(selectedPos + 1, true) :
2436                lookForSelectablePosition(selectedPos - 1, false);
2437        int amountToScroll = amountToScroll(direction, nextSelectedPosition);
2438
2439        // if we are moving focus, we may OVERRIDE the default behavior
2440        final ArrowScrollFocusResult focusResult = mItemsCanFocus ? arrowScrollFocused(direction) : null;
2441        if (focusResult != null) {
2442            nextSelectedPosition = focusResult.getSelectedPosition();
2443            amountToScroll = focusResult.getAmountToScroll();
2444        }
2445
2446        boolean needToRedraw = focusResult != null;
2447        if (nextSelectedPosition != INVALID_POSITION) {
2448            handleNewSelectionChange(selectedView, direction, nextSelectedPosition, focusResult != null);
2449            setSelectedPositionInt(nextSelectedPosition);
2450            setNextSelectedPositionInt(nextSelectedPosition);
2451            selectedView = getSelectedView();
2452            selectedPos = nextSelectedPosition;
2453            if (mItemsCanFocus && focusResult == null) {
2454                // there was no new view found to take focus, make sure we
2455                // don't leave focus with the old selection
2456                final View focused = getFocusedChild();
2457                if (focused != null) {
2458                    focused.clearFocus();
2459                }
2460            }
2461            needToRedraw = true;
2462            checkSelectionChanged();
2463        }
2464
2465        if (amountToScroll > 0) {
2466            scrollListItemsBy((direction == View.FOCUS_UP) ? amountToScroll : -amountToScroll);
2467            needToRedraw = true;
2468        }
2469
2470        // if we didn't find a new focusable, make sure any existing focused
2471        // item that was panned off screen gives up focus.
2472        if (mItemsCanFocus && (focusResult == null)
2473                && selectedView != null && selectedView.hasFocus()) {
2474            final View focused = selectedView.findFocus();
2475            if (!isViewAncestorOf(focused, this) || distanceToView(focused) > 0) {
2476                focused.clearFocus();
2477            }
2478        }
2479
2480        // if  the current selection is panned off, we need to remove the selection
2481        if (nextSelectedPosition == INVALID_POSITION && selectedView != null
2482                && !isViewAncestorOf(selectedView, this)) {
2483            selectedView = null;
2484            hideSelector();
2485
2486            // but we don't want to set the ressurect position (that would make subsequent
2487            // unhandled key events bring back the item we just scrolled off!)
2488            mResurrectToPosition = INVALID_POSITION;
2489        }
2490
2491        if (needToRedraw) {
2492            if (selectedView != null) {
2493                positionSelector(selectedPos, selectedView);
2494                mSelectedTop = selectedView.getTop();
2495            }
2496            if (!awakenScrollBars()) {
2497                invalidate();
2498            }
2499            invokeOnItemScrollListener();
2500            return true;
2501        }
2502
2503        return false;
2504    }
2505
2506    /**
2507     * When selection changes, it is possible that the previously selected or the
2508     * next selected item will change its size.  If so, we need to offset some folks,
2509     * and re-layout the items as appropriate.
2510     *
2511     * @param selectedView The currently selected view (before changing selection).
2512     *   should be <code>null</code> if there was no previous selection.
2513     * @param direction Either {@link android.view.View#FOCUS_UP} or
2514     *        {@link android.view.View#FOCUS_DOWN}.
2515     * @param newSelectedPosition The position of the next selection.
2516     * @param newFocusAssigned whether new focus was assigned.  This matters because
2517     *        when something has focus, we don't want to show selection (ugh).
2518     */
2519    private void handleNewSelectionChange(View selectedView, int direction, int newSelectedPosition,
2520            boolean newFocusAssigned) {
2521        if (newSelectedPosition == INVALID_POSITION) {
2522            throw new IllegalArgumentException("newSelectedPosition needs to be valid");
2523        }
2524
2525        // whether or not we are moving down or up, we want to preserve the
2526        // top of whatever view is on top:
2527        // - moving down: the view that had selection
2528        // - moving up: the view that is getting selection
2529        View topView;
2530        View bottomView;
2531        int topViewIndex, bottomViewIndex;
2532        boolean topSelected = false;
2533        final int selectedIndex = mSelectedPosition - mFirstPosition;
2534        final int nextSelectedIndex = newSelectedPosition - mFirstPosition;
2535        if (direction == View.FOCUS_UP) {
2536            topViewIndex = nextSelectedIndex;
2537            bottomViewIndex = selectedIndex;
2538            topView = getChildAt(topViewIndex);
2539            bottomView = selectedView;
2540            topSelected = true;
2541        } else {
2542            topViewIndex = selectedIndex;
2543            bottomViewIndex = nextSelectedIndex;
2544            topView = selectedView;
2545            bottomView = getChildAt(bottomViewIndex);
2546        }
2547
2548        final int numChildren = getChildCount();
2549
2550        // start with top view: is it changing size?
2551        if (topView != null) {
2552            topView.setSelected(!newFocusAssigned && topSelected);
2553            measureAndAdjustDown(topView, topViewIndex, numChildren);
2554        }
2555
2556        // is the bottom view changing size?
2557        if (bottomView != null) {
2558            bottomView.setSelected(!newFocusAssigned && !topSelected);
2559            measureAndAdjustDown(bottomView, bottomViewIndex, numChildren);
2560        }
2561    }
2562
2563    /**
2564     * Re-measure a child, and if its height changes, lay it out preserving its
2565     * top, and adjust the children below it appropriately.
2566     * @param child The child
2567     * @param childIndex The view group index of the child.
2568     * @param numChildren The number of children in the view group.
2569     */
2570    private void measureAndAdjustDown(View child, int childIndex, int numChildren) {
2571        int oldHeight = child.getHeight();
2572        measureItem(child);
2573        if (child.getMeasuredHeight() != oldHeight) {
2574            // lay out the view, preserving its top
2575            relayoutMeasuredItem(child);
2576
2577            // adjust views below appropriately
2578            final int heightDelta = child.getMeasuredHeight() - oldHeight;
2579            for (int i = childIndex + 1; i < numChildren; i++) {
2580                getChildAt(i).offsetTopAndBottom(heightDelta);
2581            }
2582        }
2583    }
2584
2585    /**
2586     * Measure a particular list child.
2587     * TODO: unify with setUpChild.
2588     * @param child The child.
2589     */
2590    private void measureItem(View child) {
2591        ViewGroup.LayoutParams p = child.getLayoutParams();
2592        if (p == null) {
2593            p = new ViewGroup.LayoutParams(
2594                    ViewGroup.LayoutParams.MATCH_PARENT,
2595                    ViewGroup.LayoutParams.WRAP_CONTENT);
2596        }
2597
2598        int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
2599                mListPadding.left + mListPadding.right, p.width);
2600        int lpHeight = p.height;
2601        int childHeightSpec;
2602        if (lpHeight > 0) {
2603            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
2604        } else {
2605            childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
2606        }
2607        child.measure(childWidthSpec, childHeightSpec);
2608    }
2609
2610    /**
2611     * Layout a child that has been measured, preserving its top position.
2612     * TODO: unify with setUpChild.
2613     * @param child The child.
2614     */
2615    private void relayoutMeasuredItem(View child) {
2616        final int w = child.getMeasuredWidth();
2617        final int h = child.getMeasuredHeight();
2618        final int childLeft = mListPadding.left;
2619        final int childRight = childLeft + w;
2620        final int childTop = child.getTop();
2621        final int childBottom = childTop + h;
2622        child.layout(childLeft, childTop, childRight, childBottom);
2623    }
2624
2625    /**
2626     * @return The amount to preview next items when arrow srolling.
2627     */
2628    private int getArrowScrollPreviewLength() {
2629        return Math.max(MIN_SCROLL_PREVIEW_PIXELS, getVerticalFadingEdgeLength());
2630    }
2631
2632    /**
2633     * Determine how much we need to scroll in order to get the next selected view
2634     * visible, with a fading edge showing below as applicable.  The amount is
2635     * capped at {@link #getMaxScrollAmount()} .
2636     *
2637     * @param direction either {@link android.view.View#FOCUS_UP} or
2638     *        {@link android.view.View#FOCUS_DOWN}.
2639     * @param nextSelectedPosition The position of the next selection, or
2640     *        {@link #INVALID_POSITION} if there is no next selectable position
2641     * @return The amount to scroll. Note: this is always positive!  Direction
2642     *         needs to be taken into account when actually scrolling.
2643     */
2644    private int amountToScroll(int direction, int nextSelectedPosition) {
2645        final int listBottom = getHeight() - mListPadding.bottom;
2646        final int listTop = mListPadding.top;
2647
2648        int numChildren = getChildCount();
2649
2650        if (direction == View.FOCUS_DOWN) {
2651            int indexToMakeVisible = numChildren - 1;
2652            if (nextSelectedPosition != INVALID_POSITION) {
2653                indexToMakeVisible = nextSelectedPosition - mFirstPosition;
2654            }
2655            while (numChildren <= indexToMakeVisible) {
2656                // Child to view is not attached yet.
2657                addViewBelow(getChildAt(numChildren - 1), mFirstPosition + numChildren - 1);
2658                numChildren++;
2659            }
2660            final int positionToMakeVisible = mFirstPosition + indexToMakeVisible;
2661            final View viewToMakeVisible = getChildAt(indexToMakeVisible);
2662
2663            int goalBottom = listBottom;
2664            if (positionToMakeVisible < mItemCount - 1) {
2665                goalBottom -= getArrowScrollPreviewLength();
2666            }
2667
2668            if (viewToMakeVisible.getBottom() <= goalBottom) {
2669                // item is fully visible.
2670                return 0;
2671            }
2672
2673            if (nextSelectedPosition != INVALID_POSITION
2674                    && (goalBottom - viewToMakeVisible.getTop()) >= getMaxScrollAmount()) {
2675                // item already has enough of it visible, changing selection is good enough
2676                return 0;
2677            }
2678
2679            int amountToScroll = (viewToMakeVisible.getBottom() - goalBottom);
2680
2681            if ((mFirstPosition + numChildren) == mItemCount) {
2682                // last is last in list -> make sure we don't scroll past it
2683                final int max = getChildAt(numChildren - 1).getBottom() - listBottom;
2684                amountToScroll = Math.min(amountToScroll, max);
2685            }
2686
2687            return Math.min(amountToScroll, getMaxScrollAmount());
2688        } else {
2689            int indexToMakeVisible = 0;
2690            if (nextSelectedPosition != INVALID_POSITION) {
2691                indexToMakeVisible = nextSelectedPosition - mFirstPosition;
2692            }
2693            while (indexToMakeVisible < 0) {
2694                // Child to view is not attached yet.
2695                addViewAbove(getChildAt(0), mFirstPosition);
2696                mFirstPosition--;
2697                indexToMakeVisible = nextSelectedPosition - mFirstPosition;
2698            }
2699            final int positionToMakeVisible = mFirstPosition + indexToMakeVisible;
2700            final View viewToMakeVisible = getChildAt(indexToMakeVisible);
2701            int goalTop = listTop;
2702            if (positionToMakeVisible > 0) {
2703                goalTop += getArrowScrollPreviewLength();
2704            }
2705            if (viewToMakeVisible.getTop() >= goalTop) {
2706                // item is fully visible.
2707                return 0;
2708            }
2709
2710            if (nextSelectedPosition != INVALID_POSITION &&
2711                    (viewToMakeVisible.getBottom() - goalTop) >= getMaxScrollAmount()) {
2712                // item already has enough of it visible, changing selection is good enough
2713                return 0;
2714            }
2715
2716            int amountToScroll = (goalTop - viewToMakeVisible.getTop());
2717            if (mFirstPosition == 0) {
2718                // first is first in list -> make sure we don't scroll past it
2719                final int max = listTop - getChildAt(0).getTop();
2720                amountToScroll = Math.min(amountToScroll,  max);
2721            }
2722            return Math.min(amountToScroll, getMaxScrollAmount());
2723        }
2724    }
2725
2726    /**
2727     * Holds results of focus aware arrow scrolling.
2728     */
2729    static private class ArrowScrollFocusResult {
2730        private int mSelectedPosition;
2731        private int mAmountToScroll;
2732
2733        /**
2734         * How {@link android.widget.ListView#arrowScrollFocused} returns its values.
2735         */
2736        void populate(int selectedPosition, int amountToScroll) {
2737            mSelectedPosition = selectedPosition;
2738            mAmountToScroll = amountToScroll;
2739        }
2740
2741        public int getSelectedPosition() {
2742            return mSelectedPosition;
2743        }
2744
2745        public int getAmountToScroll() {
2746            return mAmountToScroll;
2747        }
2748    }
2749
2750    /**
2751     * @param direction either {@link android.view.View#FOCUS_UP} or
2752     *        {@link android.view.View#FOCUS_DOWN}.
2753     * @return The position of the next selectable position of the views that
2754     *         are currently visible, taking into account the fact that there might
2755     *         be no selection.  Returns {@link #INVALID_POSITION} if there is no
2756     *         selectable view on screen in the given direction.
2757     */
2758    private int lookForSelectablePositionOnScreen(int direction) {
2759        final int firstPosition = mFirstPosition;
2760        if (direction == View.FOCUS_DOWN) {
2761            int startPos = (mSelectedPosition != INVALID_POSITION) ?
2762                    mSelectedPosition + 1 :
2763                    firstPosition;
2764            if (startPos >= mAdapter.getCount()) {
2765                return INVALID_POSITION;
2766            }
2767            if (startPos < firstPosition) {
2768                startPos = firstPosition;
2769            }
2770
2771            final int lastVisiblePos = getLastVisiblePosition();
2772            final ListAdapter adapter = getAdapter();
2773            for (int pos = startPos; pos <= lastVisiblePos; pos++) {
2774                if (adapter.isEnabled(pos)
2775                        && getChildAt(pos - firstPosition).getVisibility() == View.VISIBLE) {
2776                    return pos;
2777                }
2778            }
2779        } else {
2780            int last = firstPosition + getChildCount() - 1;
2781            int startPos = (mSelectedPosition != INVALID_POSITION) ?
2782                    mSelectedPosition - 1 :
2783                    firstPosition + getChildCount() - 1;
2784            if (startPos < 0 || startPos >= mAdapter.getCount()) {
2785                return INVALID_POSITION;
2786            }
2787            if (startPos > last) {
2788                startPos = last;
2789            }
2790
2791            final ListAdapter adapter = getAdapter();
2792            for (int pos = startPos; pos >= firstPosition; pos--) {
2793                if (adapter.isEnabled(pos)
2794                        && getChildAt(pos - firstPosition).getVisibility() == View.VISIBLE) {
2795                    return pos;
2796                }
2797            }
2798        }
2799        return INVALID_POSITION;
2800    }
2801
2802    /**
2803     * Do an arrow scroll based on focus searching.  If a new view is
2804     * given focus, return the selection delta and amount to scroll via
2805     * an {@link ArrowScrollFocusResult}, otherwise, return null.
2806     *
2807     * @param direction either {@link android.view.View#FOCUS_UP} or
2808     *        {@link android.view.View#FOCUS_DOWN}.
2809     * @return The result if focus has changed, or <code>null</code>.
2810     */
2811    private ArrowScrollFocusResult arrowScrollFocused(final int direction) {
2812        final View selectedView = getSelectedView();
2813        View newFocus;
2814        if (selectedView != null && selectedView.hasFocus()) {
2815            View oldFocus = selectedView.findFocus();
2816            newFocus = FocusFinder.getInstance().findNextFocus(this, oldFocus, direction);
2817        } else {
2818            if (direction == View.FOCUS_DOWN) {
2819                final boolean topFadingEdgeShowing = (mFirstPosition > 0);
2820                final int listTop = mListPadding.top +
2821                        (topFadingEdgeShowing ? getArrowScrollPreviewLength() : 0);
2822                final int ySearchPoint =
2823                        (selectedView != null && selectedView.getTop() > listTop) ?
2824                                selectedView.getTop() :
2825                                listTop;
2826                mTempRect.set(0, ySearchPoint, 0, ySearchPoint);
2827            } else {
2828                final boolean bottomFadingEdgeShowing =
2829                        (mFirstPosition + getChildCount() - 1) < mItemCount;
2830                final int listBottom = getHeight() - mListPadding.bottom -
2831                        (bottomFadingEdgeShowing ? getArrowScrollPreviewLength() : 0);
2832                final int ySearchPoint =
2833                        (selectedView != null && selectedView.getBottom() < listBottom) ?
2834                                selectedView.getBottom() :
2835                                listBottom;
2836                mTempRect.set(0, ySearchPoint, 0, ySearchPoint);
2837            }
2838            newFocus = FocusFinder.getInstance().findNextFocusFromRect(this, mTempRect, direction);
2839        }
2840
2841        if (newFocus != null) {
2842            final int positionOfNewFocus = positionOfNewFocus(newFocus);
2843
2844            // if the focus change is in a different new position, make sure
2845            // we aren't jumping over another selectable position
2846            if (mSelectedPosition != INVALID_POSITION && positionOfNewFocus != mSelectedPosition) {
2847                final int selectablePosition = lookForSelectablePositionOnScreen(direction);
2848                if (selectablePosition != INVALID_POSITION &&
2849                        ((direction == View.FOCUS_DOWN && selectablePosition < positionOfNewFocus) ||
2850                        (direction == View.FOCUS_UP && selectablePosition > positionOfNewFocus))) {
2851                    return null;
2852                }
2853            }
2854
2855            int focusScroll = amountToScrollToNewFocus(direction, newFocus, positionOfNewFocus);
2856
2857            final int maxScrollAmount = getMaxScrollAmount();
2858            if (focusScroll < maxScrollAmount) {
2859                // not moving too far, safe to give next view focus
2860                newFocus.requestFocus(direction);
2861                mArrowScrollFocusResult.populate(positionOfNewFocus, focusScroll);
2862                return mArrowScrollFocusResult;
2863            } else if (distanceToView(newFocus) < maxScrollAmount){
2864                // Case to consider:
2865                // too far to get entire next focusable on screen, but by going
2866                // max scroll amount, we are getting it at least partially in view,
2867                // so give it focus and scroll the max ammount.
2868                newFocus.requestFocus(direction);
2869                mArrowScrollFocusResult.populate(positionOfNewFocus, maxScrollAmount);
2870                return mArrowScrollFocusResult;
2871            }
2872        }
2873        return null;
2874    }
2875
2876    /**
2877     * @param newFocus The view that would have focus.
2878     * @return the position that contains newFocus
2879     */
2880    private int positionOfNewFocus(View newFocus) {
2881        final int numChildren = getChildCount();
2882        for (int i = 0; i < numChildren; i++) {
2883            final View child = getChildAt(i);
2884            if (isViewAncestorOf(newFocus, child)) {
2885                return mFirstPosition + i;
2886            }
2887        }
2888        throw new IllegalArgumentException("newFocus is not a child of any of the"
2889                + " children of the list!");
2890    }
2891
2892    /**
2893     * Return true if child is an ancestor of parent, (or equal to the parent).
2894     */
2895    private boolean isViewAncestorOf(View child, View parent) {
2896        if (child == parent) {
2897            return true;
2898        }
2899
2900        final ViewParent theParent = child.getParent();
2901        return (theParent instanceof ViewGroup) && isViewAncestorOf((View) theParent, parent);
2902    }
2903
2904    /**
2905     * Determine how much we need to scroll in order to get newFocus in view.
2906     * @param direction either {@link android.view.View#FOCUS_UP} or
2907     *        {@link android.view.View#FOCUS_DOWN}.
2908     * @param newFocus The view that would take focus.
2909     * @param positionOfNewFocus The position of the list item containing newFocus
2910     * @return The amount to scroll.  Note: this is always positive!  Direction
2911     *   needs to be taken into account when actually scrolling.
2912     */
2913    private int amountToScrollToNewFocus(int direction, View newFocus, int positionOfNewFocus) {
2914        int amountToScroll = 0;
2915        newFocus.getDrawingRect(mTempRect);
2916        offsetDescendantRectToMyCoords(newFocus, mTempRect);
2917        if (direction == View.FOCUS_UP) {
2918            if (mTempRect.top < mListPadding.top) {
2919                amountToScroll = mListPadding.top - mTempRect.top;
2920                if (positionOfNewFocus > 0) {
2921                    amountToScroll += getArrowScrollPreviewLength();
2922                }
2923            }
2924        } else {
2925            final int listBottom = getHeight() - mListPadding.bottom;
2926            if (mTempRect.bottom > listBottom) {
2927                amountToScroll = mTempRect.bottom - listBottom;
2928                if (positionOfNewFocus < mItemCount - 1) {
2929                    amountToScroll += getArrowScrollPreviewLength();
2930                }
2931            }
2932        }
2933        return amountToScroll;
2934    }
2935
2936    /**
2937     * Determine the distance to the nearest edge of a view in a particular
2938     * direction.
2939     *
2940     * @param descendant A descendant of this list.
2941     * @return The distance, or 0 if the nearest edge is already on screen.
2942     */
2943    private int distanceToView(View descendant) {
2944        int distance = 0;
2945        descendant.getDrawingRect(mTempRect);
2946        offsetDescendantRectToMyCoords(descendant, mTempRect);
2947        final int listBottom = mBottom - mTop - mListPadding.bottom;
2948        if (mTempRect.bottom < mListPadding.top) {
2949            distance = mListPadding.top - mTempRect.bottom;
2950        } else if (mTempRect.top > listBottom) {
2951            distance = mTempRect.top - listBottom;
2952        }
2953        return distance;
2954    }
2955
2956
2957    /**
2958     * Scroll the children by amount, adding a view at the end and removing
2959     * views that fall off as necessary.
2960     *
2961     * @param amount The amount (positive or negative) to scroll.
2962     */
2963    private void scrollListItemsBy(int amount) {
2964        offsetChildrenTopAndBottom(amount);
2965
2966        final int listBottom = getHeight() - mListPadding.bottom;
2967        final int listTop = mListPadding.top;
2968        final AbsListView.RecycleBin recycleBin = mRecycler;
2969
2970        if (amount < 0) {
2971            // shifted items up
2972
2973            // may need to pan views into the bottom space
2974            int numChildren = getChildCount();
2975            View last = getChildAt(numChildren - 1);
2976            while (last.getBottom() < listBottom) {
2977                final int lastVisiblePosition = mFirstPosition + numChildren - 1;
2978                if (lastVisiblePosition < mItemCount - 1) {
2979                    last = addViewBelow(last, lastVisiblePosition);
2980                    numChildren++;
2981                } else {
2982                    break;
2983                }
2984            }
2985
2986            // may have brought in the last child of the list that is skinnier
2987            // than the fading edge, thereby leaving space at the end.  need
2988            // to shift back
2989            if (last.getBottom() < listBottom) {
2990                offsetChildrenTopAndBottom(listBottom - last.getBottom());
2991            }
2992
2993            // top views may be panned off screen
2994            View first = getChildAt(0);
2995            while (first.getBottom() < listTop) {
2996                AbsListView.LayoutParams layoutParams = (LayoutParams) first.getLayoutParams();
2997                if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) {
2998                    recycleBin.addScrapView(first, mFirstPosition);
2999                }
3000                detachViewFromParent(first);
3001                first = getChildAt(0);
3002                mFirstPosition++;
3003            }
3004        } else {
3005            // shifted items down
3006            View first = getChildAt(0);
3007
3008            // may need to pan views into top
3009            while ((first.getTop() > listTop) && (mFirstPosition > 0)) {
3010                first = addViewAbove(first, mFirstPosition);
3011                mFirstPosition--;
3012            }
3013
3014            // may have brought the very first child of the list in too far and
3015            // need to shift it back
3016            if (first.getTop() > listTop) {
3017                offsetChildrenTopAndBottom(listTop - first.getTop());
3018            }
3019
3020            int lastIndex = getChildCount() - 1;
3021            View last = getChildAt(lastIndex);
3022
3023            // bottom view may be panned off screen
3024            while (last.getTop() > listBottom) {
3025                AbsListView.LayoutParams layoutParams = (LayoutParams) last.getLayoutParams();
3026                if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) {
3027                    recycleBin.addScrapView(last, mFirstPosition+lastIndex);
3028                }
3029                detachViewFromParent(last);
3030                last = getChildAt(--lastIndex);
3031            }
3032        }
3033    }
3034
3035    private View addViewAbove(View theView, int position) {
3036        int abovePosition = position - 1;
3037        View view = obtainView(abovePosition, mIsScrap);
3038        int edgeOfNewChild = theView.getTop() - mDividerHeight;
3039        setupChild(view, abovePosition, edgeOfNewChild, false, mListPadding.left,
3040                false, mIsScrap[0]);
3041        return view;
3042    }
3043
3044    private View addViewBelow(View theView, int position) {
3045        int belowPosition = position + 1;
3046        View view = obtainView(belowPosition, mIsScrap);
3047        int edgeOfNewChild = theView.getBottom() + mDividerHeight;
3048        setupChild(view, belowPosition, edgeOfNewChild, true, mListPadding.left,
3049                false, mIsScrap[0]);
3050        return view;
3051    }
3052
3053    /**
3054     * Indicates that the views created by the ListAdapter can contain focusable
3055     * items.
3056     *
3057     * @param itemsCanFocus true if items can get focus, false otherwise
3058     */
3059    public void setItemsCanFocus(boolean itemsCanFocus) {
3060        mItemsCanFocus = itemsCanFocus;
3061        if (!itemsCanFocus) {
3062            setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
3063        }
3064    }
3065
3066    /**
3067     * @return Whether the views created by the ListAdapter can contain focusable
3068     * items.
3069     */
3070    public boolean getItemsCanFocus() {
3071        return mItemsCanFocus;
3072    }
3073
3074    @Override
3075    public boolean isOpaque() {
3076        boolean retValue = (mCachingActive && mIsCacheColorOpaque && mDividerIsOpaque &&
3077                hasOpaqueScrollbars()) || super.isOpaque();
3078        if (retValue) {
3079            // only return true if the list items cover the entire area of the view
3080            final int listTop = mListPadding != null ? mListPadding.top : mPaddingTop;
3081            View first = getChildAt(0);
3082            if (first == null || first.getTop() > listTop) {
3083                return false;
3084            }
3085            final int listBottom = getHeight() -
3086                    (mListPadding != null ? mListPadding.bottom : mPaddingBottom);
3087            View last = getChildAt(getChildCount() - 1);
3088            if (last == null || last.getBottom() < listBottom) {
3089                return false;
3090            }
3091        }
3092        return retValue;
3093    }
3094
3095    @Override
3096    public void setCacheColorHint(int color) {
3097        final boolean opaque = (color >>> 24) == 0xFF;
3098        mIsCacheColorOpaque = opaque;
3099        if (opaque) {
3100            if (mDividerPaint == null) {
3101                mDividerPaint = new Paint();
3102            }
3103            mDividerPaint.setColor(color);
3104        }
3105        super.setCacheColorHint(color);
3106    }
3107
3108    void drawOverscrollHeader(Canvas canvas, Drawable drawable, Rect bounds) {
3109        final int height = drawable.getMinimumHeight();
3110
3111        canvas.save();
3112        canvas.clipRect(bounds);
3113
3114        final int span = bounds.bottom - bounds.top;
3115        if (span < height) {
3116            bounds.top = bounds.bottom - height;
3117        }
3118
3119        drawable.setBounds(bounds);
3120        drawable.draw(canvas);
3121
3122        canvas.restore();
3123    }
3124
3125    void drawOverscrollFooter(Canvas canvas, Drawable drawable, Rect bounds) {
3126        final int height = drawable.getMinimumHeight();
3127
3128        canvas.save();
3129        canvas.clipRect(bounds);
3130
3131        final int span = bounds.bottom - bounds.top;
3132        if (span < height) {
3133            bounds.bottom = bounds.top + height;
3134        }
3135
3136        drawable.setBounds(bounds);
3137        drawable.draw(canvas);
3138
3139        canvas.restore();
3140    }
3141
3142    @Override
3143    protected void dispatchDraw(Canvas canvas) {
3144        if (mCachingStarted) {
3145            mCachingActive = true;
3146        }
3147
3148        // Draw the dividers
3149        final int dividerHeight = mDividerHeight;
3150        final Drawable overscrollHeader = mOverScrollHeader;
3151        final Drawable overscrollFooter = mOverScrollFooter;
3152        final boolean drawOverscrollHeader = overscrollHeader != null;
3153        final boolean drawOverscrollFooter = overscrollFooter != null;
3154        final boolean drawDividers = dividerHeight > 0 && mDivider != null;
3155
3156        if (drawDividers || drawOverscrollHeader || drawOverscrollFooter) {
3157            // Only modify the top and bottom in the loop, we set the left and right here
3158            final Rect bounds = mTempRect;
3159            bounds.left = mPaddingLeft;
3160            bounds.right = mRight - mLeft - mPaddingRight;
3161
3162            final int count = getChildCount();
3163            final int headerCount = mHeaderViewInfos.size();
3164            final int itemCount = mItemCount;
3165            final int footerLimit = itemCount - mFooterViewInfos.size() - 1;
3166            final boolean headerDividers = mHeaderDividersEnabled;
3167            final boolean footerDividers = mFooterDividersEnabled;
3168            final int first = mFirstPosition;
3169            final boolean areAllItemsSelectable = mAreAllItemsSelectable;
3170            final ListAdapter adapter = mAdapter;
3171            // If the list is opaque *and* the background is not, we want to
3172            // fill a rect where the dividers would be for non-selectable items
3173            // If the list is opaque and the background is also opaque, we don't
3174            // need to draw anything since the background will do it for us
3175            final boolean fillForMissingDividers = isOpaque() && !super.isOpaque();
3176
3177            if (fillForMissingDividers && mDividerPaint == null && mIsCacheColorOpaque) {
3178                mDividerPaint = new Paint();
3179                mDividerPaint.setColor(getCacheColorHint());
3180            }
3181            final Paint paint = mDividerPaint;
3182
3183            int effectivePaddingTop = 0;
3184            int effectivePaddingBottom = 0;
3185            if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) {
3186                effectivePaddingTop = mListPadding.top;
3187                effectivePaddingBottom = mListPadding.bottom;
3188            }
3189
3190            final int listBottom = mBottom - mTop - effectivePaddingBottom + mScrollY;
3191            if (!mStackFromBottom) {
3192                int bottom = 0;
3193
3194                // Draw top divider or header for overscroll
3195                final int scrollY = mScrollY;
3196                if (count > 0 && scrollY < 0) {
3197                    if (drawOverscrollHeader) {
3198                        bounds.bottom = 0;
3199                        bounds.top = scrollY;
3200                        drawOverscrollHeader(canvas, overscrollHeader, bounds);
3201                    } else if (drawDividers) {
3202                        bounds.bottom = 0;
3203                        bounds.top = -dividerHeight;
3204                        drawDivider(canvas, bounds, -1);
3205                    }
3206                }
3207
3208                for (int i = 0; i < count; i++) {
3209                    if ((headerDividers || first + i >= headerCount) &&
3210                            (footerDividers || first + i < footerLimit)) {
3211                        View child = getChildAt(i);
3212                        bottom = child.getBottom();
3213                        // Don't draw dividers next to items that are not enabled
3214
3215                        if (drawDividers &&
3216                                (bottom < listBottom && !(drawOverscrollFooter && i == count - 1))) {
3217                            if ((areAllItemsSelectable ||
3218                                    (adapter.isEnabled(first + i) && (i == count - 1 ||
3219                                            adapter.isEnabled(first + i + 1))))) {
3220                                bounds.top = bottom;
3221                                bounds.bottom = bottom + dividerHeight;
3222                                drawDivider(canvas, bounds, i);
3223                            } else if (fillForMissingDividers) {
3224                                bounds.top = bottom;
3225                                bounds.bottom = bottom + dividerHeight;
3226                                canvas.drawRect(bounds, paint);
3227                            }
3228                        }
3229                    }
3230                }
3231
3232                final int overFooterBottom = mBottom + mScrollY;
3233                if (drawOverscrollFooter && first + count == itemCount &&
3234                        overFooterBottom > bottom) {
3235                    bounds.top = bottom;
3236                    bounds.bottom = overFooterBottom;
3237                    drawOverscrollFooter(canvas, overscrollFooter, bounds);
3238                }
3239            } else {
3240                int top;
3241
3242                final int scrollY = mScrollY;
3243
3244                if (count > 0 && drawOverscrollHeader) {
3245                    bounds.top = scrollY;
3246                    bounds.bottom = getChildAt(0).getTop();
3247                    drawOverscrollHeader(canvas, overscrollHeader, bounds);
3248                }
3249
3250                final int start = drawOverscrollHeader ? 1 : 0;
3251                for (int i = start; i < count; i++) {
3252                    if ((headerDividers || first + i >= headerCount) &&
3253                            (footerDividers || first + i < footerLimit)) {
3254                        View child = getChildAt(i);
3255                        top = child.getTop();
3256                        // Don't draw dividers next to items that are not enabled
3257                        if (top > effectivePaddingTop) {
3258                            if ((areAllItemsSelectable ||
3259                                    (adapter.isEnabled(first + i) && (i == count - 1 ||
3260                                            adapter.isEnabled(first + i + 1))))) {
3261                                bounds.top = top - dividerHeight;
3262                                bounds.bottom = top;
3263                                // Give the method the child ABOVE the divider, so we
3264                                // subtract one from our child
3265                                // position. Give -1 when there is no child above the
3266                                // divider.
3267                                drawDivider(canvas, bounds, i - 1);
3268                            } else if (fillForMissingDividers) {
3269                                bounds.top = top - dividerHeight;
3270                                bounds.bottom = top;
3271                                canvas.drawRect(bounds, paint);
3272                            }
3273                        }
3274                    }
3275                }
3276
3277                if (count > 0 && scrollY > 0) {
3278                    if (drawOverscrollFooter) {
3279                        final int absListBottom = mBottom;
3280                        bounds.top = absListBottom;
3281                        bounds.bottom = absListBottom + scrollY;
3282                        drawOverscrollFooter(canvas, overscrollFooter, bounds);
3283                    } else if (drawDividers) {
3284                        bounds.top = listBottom;
3285                        bounds.bottom = listBottom + dividerHeight;
3286                        drawDivider(canvas, bounds, -1);
3287                    }
3288                }
3289            }
3290        }
3291
3292        // Draw the indicators (these should be drawn above the dividers) and children
3293        super.dispatchDraw(canvas);
3294    }
3295
3296    @Override
3297    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
3298        boolean more = super.drawChild(canvas, child, drawingTime);
3299        if (mCachingActive && child.mCachingFailed) {
3300            mCachingActive = false;
3301        }
3302        return more;
3303    }
3304
3305    /**
3306     * Draws a divider for the given child in the given bounds.
3307     *
3308     * @param canvas The canvas to draw to.
3309     * @param bounds The bounds of the divider.
3310     * @param childIndex The index of child (of the View) above the divider.
3311     *            This will be -1 if there is no child above the divider to be
3312     *            drawn.
3313     */
3314    void drawDivider(Canvas canvas, Rect bounds, int childIndex) {
3315        // This widget draws the same divider for all children
3316        final Drawable divider = mDivider;
3317
3318        divider.setBounds(bounds);
3319        divider.draw(canvas);
3320    }
3321
3322    /**
3323     * Returns the drawable that will be drawn between each item in the list.
3324     *
3325     * @return the current drawable drawn between list elements
3326     */
3327    public Drawable getDivider() {
3328        return mDivider;
3329    }
3330
3331    /**
3332     * Sets the drawable that will be drawn between each item in the list. If the drawable does
3333     * not have an intrinsic height, you should also call {@link #setDividerHeight(int)}
3334     *
3335     * @param divider The drawable to use.
3336     */
3337    public void setDivider(Drawable divider) {
3338        if (divider != null) {
3339            mDividerHeight = divider.getIntrinsicHeight();
3340        } else {
3341            mDividerHeight = 0;
3342        }
3343        mDivider = divider;
3344        mDividerIsOpaque = divider == null || divider.getOpacity() == PixelFormat.OPAQUE;
3345        requestLayout();
3346        invalidate();
3347    }
3348
3349    /**
3350     * @return Returns the height of the divider that will be drawn between each item in the list.
3351     */
3352    public int getDividerHeight() {
3353        return mDividerHeight;
3354    }
3355
3356    /**
3357     * Sets the height of the divider that will be drawn between each item in the list. Calling
3358     * this will override the intrinsic height as set by {@link #setDivider(Drawable)}
3359     *
3360     * @param height The new height of the divider in pixels.
3361     */
3362    public void setDividerHeight(int height) {
3363        mDividerHeight = height;
3364        requestLayout();
3365        invalidate();
3366    }
3367
3368    /**
3369     * Enables or disables the drawing of the divider for header views.
3370     *
3371     * @param headerDividersEnabled True to draw the headers, false otherwise.
3372     *
3373     * @see #setFooterDividersEnabled(boolean)
3374     * @see #addHeaderView(android.view.View)
3375     */
3376    public void setHeaderDividersEnabled(boolean headerDividersEnabled) {
3377        mHeaderDividersEnabled = headerDividersEnabled;
3378        invalidate();
3379    }
3380
3381    /**
3382     * Enables or disables the drawing of the divider for footer views.
3383     *
3384     * @param footerDividersEnabled True to draw the footers, false otherwise.
3385     *
3386     * @see #setHeaderDividersEnabled(boolean)
3387     * @see #addFooterView(android.view.View)
3388     */
3389    public void setFooterDividersEnabled(boolean footerDividersEnabled) {
3390        mFooterDividersEnabled = footerDividersEnabled;
3391        invalidate();
3392    }
3393
3394    /**
3395     * Sets the drawable that will be drawn above all other list content.
3396     * This area can become visible when the user overscrolls the list.
3397     *
3398     * @param header The drawable to use
3399     */
3400    public void setOverscrollHeader(Drawable header) {
3401        mOverScrollHeader = header;
3402        if (mScrollY < 0) {
3403            invalidate();
3404        }
3405    }
3406
3407    /**
3408     * @return The drawable that will be drawn above all other list content
3409     */
3410    public Drawable getOverscrollHeader() {
3411        return mOverScrollHeader;
3412    }
3413
3414    /**
3415     * Sets the drawable that will be drawn below all other list content.
3416     * This area can become visible when the user overscrolls the list,
3417     * or when the list's content does not fully fill the container area.
3418     *
3419     * @param footer The drawable to use
3420     */
3421    public void setOverscrollFooter(Drawable footer) {
3422        mOverScrollFooter = footer;
3423        invalidate();
3424    }
3425
3426    /**
3427     * @return The drawable that will be drawn below all other list content
3428     */
3429    public Drawable getOverscrollFooter() {
3430        return mOverScrollFooter;
3431    }
3432
3433    @Override
3434    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3435        super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
3436
3437        final ListAdapter adapter = mAdapter;
3438        int closetChildIndex = -1;
3439        int closestChildTop = 0;
3440        if (adapter != null && gainFocus && previouslyFocusedRect != null) {
3441            previouslyFocusedRect.offset(mScrollX, mScrollY);
3442
3443            // Don't cache the result of getChildCount or mFirstPosition here,
3444            // it could change in layoutChildren.
3445            if (adapter.getCount() < getChildCount() + mFirstPosition) {
3446                mLayoutMode = LAYOUT_NORMAL;
3447                layoutChildren();
3448            }
3449
3450            // figure out which item should be selected based on previously
3451            // focused rect
3452            Rect otherRect = mTempRect;
3453            int minDistance = Integer.MAX_VALUE;
3454            final int childCount = getChildCount();
3455            final int firstPosition = mFirstPosition;
3456
3457            for (int i = 0; i < childCount; i++) {
3458                // only consider selectable views
3459                if (!adapter.isEnabled(firstPosition + i)) {
3460                    continue;
3461                }
3462
3463                View other = getChildAt(i);
3464                other.getDrawingRect(otherRect);
3465                offsetDescendantRectToMyCoords(other, otherRect);
3466                int distance = getDistance(previouslyFocusedRect, otherRect, direction);
3467
3468                if (distance < minDistance) {
3469                    minDistance = distance;
3470                    closetChildIndex = i;
3471                    closestChildTop = other.getTop();
3472                }
3473            }
3474        }
3475
3476        if (closetChildIndex >= 0) {
3477            setSelectionFromTop(closetChildIndex + mFirstPosition, closestChildTop);
3478        } else {
3479            requestLayout();
3480        }
3481    }
3482
3483
3484    /*
3485     * (non-Javadoc)
3486     *
3487     * Children specified in XML are assumed to be header views. After we have
3488     * parsed them move them out of the children list and into mHeaderViews.
3489     */
3490    @Override
3491    protected void onFinishInflate() {
3492        super.onFinishInflate();
3493
3494        int count = getChildCount();
3495        if (count > 0) {
3496            for (int i = 0; i < count; ++i) {
3497                addHeaderView(getChildAt(i));
3498            }
3499            removeAllViews();
3500        }
3501    }
3502
3503    /* (non-Javadoc)
3504     * @see android.view.View#findViewById(int)
3505     * First look in our children, then in any header and footer views that may be scrolled off.
3506     */
3507    @Override
3508    protected View findViewTraversal(int id) {
3509        View v;
3510        v = super.findViewTraversal(id);
3511        if (v == null) {
3512            v = findViewInHeadersOrFooters(mHeaderViewInfos, id);
3513            if (v != null) {
3514                return v;
3515            }
3516            v = findViewInHeadersOrFooters(mFooterViewInfos, id);
3517            if (v != null) {
3518                return v;
3519            }
3520        }
3521        return v;
3522    }
3523
3524    /* (non-Javadoc)
3525     *
3526     * Look in the passed in list of headers or footers for the view.
3527     */
3528    View findViewInHeadersOrFooters(ArrayList<FixedViewInfo> where, int id) {
3529        if (where != null) {
3530            int len = where.size();
3531            View v;
3532
3533            for (int i = 0; i < len; i++) {
3534                v = where.get(i).view;
3535
3536                if (!v.isRootNamespace()) {
3537                    v = v.findViewById(id);
3538
3539                    if (v != null) {
3540                        return v;
3541                    }
3542                }
3543            }
3544        }
3545        return null;
3546    }
3547
3548    /* (non-Javadoc)
3549     * @see android.view.View#findViewWithTag(Object)
3550     * First look in our children, then in any header and footer views that may be scrolled off.
3551     */
3552    @Override
3553    protected View findViewWithTagTraversal(Object tag) {
3554        View v;
3555        v = super.findViewWithTagTraversal(tag);
3556        if (v == null) {
3557            v = findViewWithTagInHeadersOrFooters(mHeaderViewInfos, tag);
3558            if (v != null) {
3559                return v;
3560            }
3561
3562            v = findViewWithTagInHeadersOrFooters(mFooterViewInfos, tag);
3563            if (v != null) {
3564                return v;
3565            }
3566        }
3567        return v;
3568    }
3569
3570    /* (non-Javadoc)
3571     *
3572     * Look in the passed in list of headers or footers for the view with the tag.
3573     */
3574    View findViewWithTagInHeadersOrFooters(ArrayList<FixedViewInfo> where, Object tag) {
3575        if (where != null) {
3576            int len = where.size();
3577            View v;
3578
3579            for (int i = 0; i < len; i++) {
3580                v = where.get(i).view;
3581
3582                if (!v.isRootNamespace()) {
3583                    v = v.findViewWithTag(tag);
3584
3585                    if (v != null) {
3586                        return v;
3587                    }
3588                }
3589            }
3590        }
3591        return null;
3592    }
3593
3594    /**
3595     * @hide
3596     * @see android.view.View#findViewByPredicate(Predicate)
3597     * First look in our children, then in any header and footer views that may be scrolled off.
3598     */
3599    @Override
3600    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
3601        View v;
3602        v = super.findViewByPredicateTraversal(predicate, childToSkip);
3603        if (v == null) {
3604            v = findViewByPredicateInHeadersOrFooters(mHeaderViewInfos, predicate, childToSkip);
3605            if (v != null) {
3606                return v;
3607            }
3608
3609            v = findViewByPredicateInHeadersOrFooters(mFooterViewInfos, predicate, childToSkip);
3610            if (v != null) {
3611                return v;
3612            }
3613        }
3614        return v;
3615    }
3616
3617    /* (non-Javadoc)
3618     *
3619     * Look in the passed in list of headers or footers for the first view that matches
3620     * the predicate.
3621     */
3622    View findViewByPredicateInHeadersOrFooters(ArrayList<FixedViewInfo> where,
3623            Predicate<View> predicate, View childToSkip) {
3624        if (where != null) {
3625            int len = where.size();
3626            View v;
3627
3628            for (int i = 0; i < len; i++) {
3629                v = where.get(i).view;
3630
3631                if (v != childToSkip && !v.isRootNamespace()) {
3632                    v = v.findViewByPredicate(predicate);
3633
3634                    if (v != null) {
3635                        return v;
3636                    }
3637                }
3638            }
3639        }
3640        return null;
3641    }
3642
3643    /**
3644     * Returns the set of checked items ids. The result is only valid if the
3645     * choice mode has not been set to {@link #CHOICE_MODE_NONE}.
3646     *
3647     * @return A new array which contains the id of each checked item in the
3648     *         list.
3649     *
3650     * @deprecated Use {@link #getCheckedItemIds()} instead.
3651     */
3652    @Deprecated
3653    public long[] getCheckItemIds() {
3654        // Use new behavior that correctly handles stable ID mapping.
3655        if (mAdapter != null && mAdapter.hasStableIds()) {
3656            return getCheckedItemIds();
3657        }
3658
3659        // Old behavior was buggy, but would sort of work for adapters without stable IDs.
3660        // Fall back to it to support legacy apps.
3661        if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null && mAdapter != null) {
3662            final SparseBooleanArray states = mCheckStates;
3663            final int count = states.size();
3664            final long[] ids = new long[count];
3665            final ListAdapter adapter = mAdapter;
3666
3667            int checkedCount = 0;
3668            for (int i = 0; i < count; i++) {
3669                if (states.valueAt(i)) {
3670                    ids[checkedCount++] = adapter.getItemId(states.keyAt(i));
3671                }
3672            }
3673
3674            // Trim array if needed. mCheckStates may contain false values
3675            // resulting in checkedCount being smaller than count.
3676            if (checkedCount == count) {
3677                return ids;
3678            } else {
3679                final long[] result = new long[checkedCount];
3680                System.arraycopy(ids, 0, result, 0, checkedCount);
3681
3682                return result;
3683            }
3684        }
3685        return new long[0];
3686    }
3687
3688    @Override
3689    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
3690        super.onInitializeAccessibilityEvent(event);
3691        event.setClassName(ListView.class.getName());
3692    }
3693
3694    @Override
3695    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
3696        super.onInitializeAccessibilityNodeInfo(info);
3697        info.setClassName(ListView.class.getName());
3698    }
3699}
3700