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