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