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