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