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