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