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