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