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