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