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