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