blob: e37ccf81a1e4a8671fc0dcf56eb823f2ecc70800 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -080019import com.android.internal.R;
Jeff Brown4e6319b2010-12-13 10:36:51 -080020import com.android.internal.util.Predicate;
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -080021import com.google.android.collect.Lists;
22
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.Context;
Winson Chung499cb9f2010-07-16 11:18:17 -070024import android.content.Intent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.res.TypedArray;
26import android.graphics.Canvas;
Romain Guy8f1344f2009-05-15 16:03:59 -070027import android.graphics.Paint;
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -080028import android.graphics.PixelFormat;
29import android.graphics.Rect;
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -080030import android.graphics.drawable.Drawable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.util.AttributeSet;
32import android.util.SparseBooleanArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.view.FocusFinder;
34import android.view.KeyEvent;
35import android.view.MotionEvent;
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -080036import android.view.SoundEffectConstants;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.view.View;
38import android.view.ViewDebug;
39import android.view.ViewGroup;
40import android.view.ViewParent;
svetoslavganov75986cf2009-05-14 22:28:01 -070041import android.view.accessibility.AccessibilityEvent;
Winson Chung499cb9f2010-07-16 11:18:17 -070042import android.widget.RemoteViews.RemoteView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import java.util.ArrayList;
45
46/*
47 * Implementation Notes:
48 *
49 * Some terminology:
50 *
51 * index - index of the items that are currently visible
52 * position - index of the items in the cursor
53 */
54
55
56/**
57 * A view that shows items in a vertically scrolling list. The items
58 * come from the {@link ListAdapter} associated with this view.
59 *
Scott Main41ec6532010-08-19 16:57:07 -070060 * <p>See the <a href="{@docRoot}resources/tutorials/views/hello-listview.html">List View
61 * tutorial</a>.</p>
62 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063 * @attr ref android.R.styleable#ListView_entries
64 * @attr ref android.R.styleable#ListView_divider
65 * @attr ref android.R.styleable#ListView_dividerHeight
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 * @attr ref android.R.styleable#ListView_headerDividersEnabled
67 * @attr ref android.R.styleable#ListView_footerDividersEnabled
68 */
Winson Chung499cb9f2010-07-16 11:18:17 -070069@RemoteView
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070public class ListView extends AbsListView {
71 /**
72 * Used to indicate a no preference for a position type.
73 */
74 static final int NO_POSITION = -1;
75
76 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 * When arrow scrolling, ListView will never scroll more than this factor
78 * times the height of the list.
79 */
80 private static final float MAX_SCROLL_FACTOR = 0.33f;
81
82 /**
83 * When arrow scrolling, need a certain amount of pixels to preview next
84 * items. This is usually the fading edge, but if that is small enough,
85 * we want to make sure we preview at least this many pixels.
86 */
87 private static final int MIN_SCROLL_PREVIEW_PIXELS = 2;
88
89 /**
90 * A class that represents a fixed view in a list, for example a header at the top
91 * or a footer at the bottom.
92 */
93 public class FixedViewInfo {
94 /** The view to add to the list */
95 public View view;
96 /** The data backing the view. This is returned from {@link ListAdapter#getItem(int)}. */
97 public Object data;
98 /** <code>true</code> if the fixed view should be selectable in the list */
99 public boolean isSelectable;
100 }
101
102 private ArrayList<FixedViewInfo> mHeaderViewInfos = Lists.newArrayList();
103 private ArrayList<FixedViewInfo> mFooterViewInfos = Lists.newArrayList();
104
105 Drawable mDivider;
106 int mDividerHeight;
Adam Cohenfb603862010-12-17 12:03:17 -0800107
Adam Powell637d3372010-08-25 14:37:03 -0700108 Drawable mOverScrollHeader;
109 Drawable mOverScrollFooter;
110
Romain Guy24443ea2009-05-11 11:56:30 -0700111 private boolean mIsCacheColorOpaque;
112 private boolean mDividerIsOpaque;
Romain Guy24443ea2009-05-11 11:56:30 -0700113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 private boolean mHeaderDividersEnabled;
115 private boolean mFooterDividersEnabled;
116
117 private boolean mAreAllItemsSelectable = true;
118
119 private boolean mItemsCanFocus = false;
120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 // used for temporary calculations.
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700122 private final Rect mTempRect = new Rect();
Romain Guya02903f2009-05-23 13:26:46 -0700123 private Paint mDividerPaint;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124
125 // the single allocated result per list view; kinda cheesey but avoids
126 // allocating these thingies too often.
Romain Guy9c3184cc2010-02-25 17:32:54 -0800127 private final ArrowScrollFocusResult mArrowScrollFocusResult = new ArrowScrollFocusResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128
Adam Powell9bf3c122010-02-26 11:32:07 -0800129 // Keeps focused children visible through resizes
130 private FocusSelector mFocusSelector;
Adam Powell8350f7d2010-07-28 14:27:28 -0700131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 public ListView(Context context) {
133 this(context, null);
134 }
135
136 public ListView(Context context, AttributeSet attrs) {
137 this(context, attrs, com.android.internal.R.attr.listViewStyle);
138 }
139
140 public ListView(Context context, AttributeSet attrs, int defStyle) {
141 super(context, attrs, defStyle);
142
143 TypedArray a = context.obtainStyledAttributes(attrs,
144 com.android.internal.R.styleable.ListView, defStyle, 0);
145
146 CharSequence[] entries = a.getTextArray(
147 com.android.internal.R.styleable.ListView_entries);
148 if (entries != null) {
149 setAdapter(new ArrayAdapter<CharSequence>(context,
150 com.android.internal.R.layout.simple_list_item_1, entries));
151 }
152
153 final Drawable d = a.getDrawable(com.android.internal.R.styleable.ListView_divider);
154 if (d != null) {
155 // If a divider is specified use its intrinsic height for divider height
156 setDivider(d);
157 }
Adam Powellbfb5d4b2010-03-10 18:55:25 -0800158
Adam Powell637d3372010-08-25 14:37:03 -0700159 final Drawable osHeader = a.getDrawable(
160 com.android.internal.R.styleable.ListView_overScrollHeader);
161 if (osHeader != null) {
162 setOverscrollHeader(osHeader);
163 }
164
165 final Drawable osFooter = a.getDrawable(
166 com.android.internal.R.styleable.ListView_overScrollFooter);
167 if (osFooter != null) {
168 setOverscrollFooter(osFooter);
169 }
170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 // Use the height specified, zero being the default
172 final int dividerHeight = a.getDimensionPixelSize(
173 com.android.internal.R.styleable.ListView_dividerHeight, 0);
174 if (dividerHeight != 0) {
175 setDividerHeight(dividerHeight);
176 }
177
178 mHeaderDividersEnabled = a.getBoolean(R.styleable.ListView_headerDividersEnabled, true);
179 mFooterDividersEnabled = a.getBoolean(R.styleable.ListView_footerDividersEnabled, true);
180
181 a.recycle();
182 }
183
184 /**
185 * @return The maximum amount a list view will scroll in response to
186 * an arrow event.
187 */
188 public int getMaxScrollAmount() {
189 return (int) (MAX_SCROLL_FACTOR * (mBottom - mTop));
190 }
191
192 /**
193 * Make sure views are touching the top or bottom edge, as appropriate for
194 * our gravity
195 */
196 private void adjustViewsUpOrDown() {
197 final int childCount = getChildCount();
198 int delta;
199
200 if (childCount > 0) {
201 View child;
202
203 if (!mStackFromBottom) {
204 // Uh-oh -- we came up short. Slide all views up to make them
205 // align with the top
206 child = getChildAt(0);
207 delta = child.getTop() - mListPadding.top;
208 if (mFirstPosition != 0) {
209 // It's OK to have some space above the first item if it is
210 // part of the vertical spacing
211 delta -= mDividerHeight;
212 }
213 if (delta < 0) {
214 // We only are looking to see if we are too low, not too high
215 delta = 0;
216 }
217 } else {
218 // we are too high, slide all views down to align with bottom
219 child = getChildAt(childCount - 1);
220 delta = child.getBottom() - (getHeight() - mListPadding.bottom);
221
222 if (mFirstPosition + childCount < mItemCount) {
223 // It's OK to have some space below the last item if it is
224 // part of the vertical spacing
225 delta += mDividerHeight;
226 }
227
228 if (delta > 0) {
229 delta = 0;
230 }
231 }
232
233 if (delta != 0) {
234 offsetChildrenTopAndBottom(-delta);
235 }
236 }
237 }
238
239 /**
240 * Add a fixed view to appear at the top of the list. If addHeaderView is
241 * called more than once, the views will appear in the order they were
242 * added. Views added using this call can take focus if they want.
243 * <p>
244 * NOTE: Call this before calling setAdapter. This is so ListView can wrap
Gilles Debunne176f9fc2010-03-02 11:00:50 -0800245 * the supplied cursor with one that will also account for header and footer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 * views.
247 *
248 * @param v The view to add.
249 * @param data Data to associate with this view
250 * @param isSelectable whether the item is selectable
251 */
252 public void addHeaderView(View v, Object data, boolean isSelectable) {
253
Marco Nelissen22c04a32011-04-19 14:07:55 -0700254 if (mAdapter != null && ! (mAdapter instanceof HeaderViewListAdapter)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 throw new IllegalStateException(
256 "Cannot add header view to list -- setAdapter has already been called.");
257 }
258
259 FixedViewInfo info = new FixedViewInfo();
260 info.view = v;
261 info.data = data;
262 info.isSelectable = isSelectable;
263 mHeaderViewInfos.add(info);
Marco Nelissen22c04a32011-04-19 14:07:55 -0700264
265 // in the case of re-adding a header view, or adding one later on,
266 // we need to notify the observer
Adam Powell247a0f02011-09-13 13:11:29 -0700267 if (mAdapter != null && mDataSetObserver != null) {
Marco Nelissen22c04a32011-04-19 14:07:55 -0700268 mDataSetObserver.onChanged();
269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 }
271
272 /**
273 * Add a fixed view to appear at the top of the list. If addHeaderView is
274 * called more than once, the views will appear in the order they were
275 * added. Views added using this call can take focus if they want.
276 * <p>
277 * NOTE: Call this before calling setAdapter. This is so ListView can wrap
Gilles Debunne176f9fc2010-03-02 11:00:50 -0800278 * the supplied cursor with one that will also account for header and footer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 * views.
280 *
281 * @param v The view to add.
282 */
283 public void addHeaderView(View v) {
284 addHeaderView(v, null, true);
285 }
286
287 @Override
288 public int getHeaderViewsCount() {
289 return mHeaderViewInfos.size();
290 }
291
292 /**
293 * Removes a previously-added header view.
294 *
295 * @param v The view to remove
296 * @return true if the view was removed, false if the view was not a header
297 * view
298 */
299 public boolean removeHeaderView(View v) {
300 if (mHeaderViewInfos.size() > 0) {
301 boolean result = false;
Adam Powell247a0f02011-09-13 13:11:29 -0700302 if (mAdapter != null && ((HeaderViewListAdapter) mAdapter).removeHeader(v)) {
Marco Nelissen22c04a32011-04-19 14:07:55 -0700303 if (mDataSetObserver != null) {
304 mDataSetObserver.onChanged();
305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 result = true;
307 }
308 removeFixedViewInfo(v, mHeaderViewInfos);
309 return result;
310 }
311 return false;
312 }
313
314 private void removeFixedViewInfo(View v, ArrayList<FixedViewInfo> where) {
315 int len = where.size();
316 for (int i = 0; i < len; ++i) {
317 FixedViewInfo info = where.get(i);
318 if (info.view == v) {
319 where.remove(i);
320 break;
321 }
322 }
323 }
324
325 /**
326 * Add a fixed view to appear at the bottom of the list. If addFooterView is
327 * called more than once, the views will appear in the order they were
328 * added. Views added using this call can take focus if they want.
329 * <p>
330 * NOTE: Call this before calling setAdapter. This is so ListView can wrap
Gilles Debunne176f9fc2010-03-02 11:00:50 -0800331 * the supplied cursor with one that will also account for header and footer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 * views.
333 *
334 * @param v The view to add.
335 * @param data Data to associate with this view
336 * @param isSelectable true if the footer view can be selected
337 */
338 public void addFooterView(View v, Object data, boolean isSelectable) {
Marco Nelissen22c04a32011-04-19 14:07:55 -0700339
Marco Nelissen63f96892011-04-20 13:42:25 -0700340 // NOTE: do not enforce the adapter being null here, since unlike in
341 // addHeaderView, it was never enforced here, and so existing apps are
342 // relying on being able to add a footer and then calling setAdapter to
343 // force creation of the HeaderViewListAdapter wrapper
Marco Nelissen22c04a32011-04-19 14:07:55 -0700344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 FixedViewInfo info = new FixedViewInfo();
346 info.view = v;
347 info.data = data;
348 info.isSelectable = isSelectable;
349 mFooterViewInfos.add(info);
350
351 // in the case of re-adding a footer view, or adding one later on,
352 // we need to notify the observer
Adam Powell247a0f02011-09-13 13:11:29 -0700353 if (mAdapter != null && mDataSetObserver != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 mDataSetObserver.onChanged();
355 }
356 }
357
358 /**
359 * Add a fixed view to appear at the bottom of the list. If addFooterView is called more
360 * than once, the views will appear in the order they were added. Views added using
361 * this call can take focus if they want.
362 * <p>NOTE: Call this before calling setAdapter. This is so ListView can wrap the supplied
Gilles Debunne176f9fc2010-03-02 11:00:50 -0800363 * cursor with one that will also account for header and footer views.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 *
365 *
366 * @param v The view to add.
367 */
368 public void addFooterView(View v) {
369 addFooterView(v, null, true);
370 }
371
372 @Override
373 public int getFooterViewsCount() {
374 return mFooterViewInfos.size();
375 }
376
377 /**
378 * Removes a previously-added footer view.
379 *
380 * @param v The view to remove
381 * @return
382 * true if the view was removed, false if the view was not a footer view
383 */
384 public boolean removeFooterView(View v) {
385 if (mFooterViewInfos.size() > 0) {
386 boolean result = false;
Adam Powell247a0f02011-09-13 13:11:29 -0700387 if (mAdapter != null && ((HeaderViewListAdapter) mAdapter).removeFooter(v)) {
Marco Nelissen22c04a32011-04-19 14:07:55 -0700388 if (mDataSetObserver != null) {
389 mDataSetObserver.onChanged();
390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 result = true;
392 }
393 removeFixedViewInfo(v, mFooterViewInfos);
394 return result;
395 }
396 return false;
397 }
398
399 /**
400 * Returns the adapter currently in use in this ListView. The returned adapter
401 * might not be the same adapter passed to {@link #setAdapter(ListAdapter)} but
402 * might be a {@link WrapperListAdapter}.
403 *
404 * @return The adapter currently used to display data in this ListView.
405 *
406 * @see #setAdapter(ListAdapter)
407 */
408 @Override
409 public ListAdapter getAdapter() {
410 return mAdapter;
411 }
412
413 /**
Winson Chung499cb9f2010-07-16 11:18:17 -0700414 * Sets up this AbsListView to use a remote views adapter which connects to a RemoteViewsService
415 * through the specified intent.
416 * @param intent the intent used to identify the RemoteViewsService for the adapter to connect to.
417 */
418 @android.view.RemotableViewMethod
419 public void setRemoteViewsAdapter(Intent intent) {
420 super.setRemoteViewsAdapter(intent);
421 }
422
423 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 * Sets the data behind this ListView.
425 *
426 * The adapter passed to this method may be wrapped by a {@link WrapperListAdapter},
427 * depending on the ListView features currently in use. For instance, adding
428 * headers and/or footers will cause the adapter to be wrapped.
429 *
430 * @param adapter The ListAdapter which is responsible for maintaining the
431 * data backing this list and for producing a view to represent an
432 * item in that data set.
433 *
434 * @see #getAdapter()
435 */
436 @Override
437 public void setAdapter(ListAdapter adapter) {
Romain Guydf36b052010-05-19 21:13:20 -0700438 if (mAdapter != null && mDataSetObserver != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 mAdapter.unregisterDataSetObserver(mDataSetObserver);
440 }
441
442 resetList();
443 mRecycler.clear();
444
445 if (mHeaderViewInfos.size() > 0|| mFooterViewInfos.size() > 0) {
446 mAdapter = new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, adapter);
447 } else {
448 mAdapter = adapter;
449 }
450
451 mOldSelectedPosition = INVALID_POSITION;
452 mOldSelectedRowId = INVALID_ROW_ID;
Adam Powellf343e1b2010-08-13 18:27:04 -0700453
454 // AbsListView#setAdapter will update choice mode states.
455 super.setAdapter(adapter);
456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 if (mAdapter != null) {
458 mAreAllItemsSelectable = mAdapter.areAllItemsEnabled();
459 mOldItemCount = mItemCount;
460 mItemCount = mAdapter.getCount();
461 checkFocus();
462
463 mDataSetObserver = new AdapterDataSetObserver();
464 mAdapter.registerDataSetObserver(mDataSetObserver);
465
466 mRecycler.setViewTypeCount(mAdapter.getViewTypeCount());
467
468 int position;
469 if (mStackFromBottom) {
470 position = lookForSelectablePosition(mItemCount - 1, false);
471 } else {
472 position = lookForSelectablePosition(0, true);
473 }
474 setSelectedPositionInt(position);
475 setNextSelectedPositionInt(position);
476
477 if (mItemCount == 0) {
478 // Nothing selected
479 checkSelectionChanged();
480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 } else {
482 mAreAllItemsSelectable = true;
483 checkFocus();
484 // Nothing selected
485 checkSelectionChanged();
486 }
487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 requestLayout();
489 }
490
491
492 /**
493 * The list is empty. Clear everything out.
494 */
495 @Override
496 void resetList() {
Romain Guy2e447d42009-04-28 18:01:24 -0700497 // The parent's resetList() will remove all views from the layout so we need to
498 // cleanup the state of our footers and headers
499 clearRecycledState(mHeaderViewInfos);
500 clearRecycledState(mFooterViewInfos);
501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 super.resetList();
Romain Guy2e447d42009-04-28 18:01:24 -0700503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 mLayoutMode = LAYOUT_NORMAL;
505 }
506
Romain Guy2e447d42009-04-28 18:01:24 -0700507 private void clearRecycledState(ArrayList<FixedViewInfo> infos) {
508 if (infos != null) {
509 final int count = infos.size();
510
511 for (int i = 0; i < count; i++) {
512 final View child = infos.get(i).view;
513 final LayoutParams p = (LayoutParams) child.getLayoutParams();
514 if (p != null) {
515 p.recycledHeaderFooter = false;
516 }
517 }
518 }
519 }
520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 /**
522 * @return Whether the list needs to show the top fading edge
523 */
524 private boolean showingTopFadingEdge() {
525 final int listTop = mScrollY + mListPadding.top;
526 return (mFirstPosition > 0) || (getChildAt(0).getTop() > listTop);
527 }
528
529 /**
530 * @return Whether the list needs to show the bottom fading edge
531 */
532 private boolean showingBottomFadingEdge() {
533 final int childCount = getChildCount();
534 final int bottomOfBottomChild = getChildAt(childCount - 1).getBottom();
535 final int lastVisiblePosition = mFirstPosition + childCount - 1;
536
537 final int listBottom = mScrollY + getHeight() - mListPadding.bottom;
538
539 return (lastVisiblePosition < mItemCount - 1)
540 || (bottomOfBottomChild < listBottom);
541 }
542
543
544 @Override
545 public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) {
546
547 int rectTopWithinChild = rect.top;
548
549 // offset so rect is in coordinates of the this view
550 rect.offset(child.getLeft(), child.getTop());
551 rect.offset(-child.getScrollX(), -child.getScrollY());
552
553 final int height = getHeight();
554 int listUnfadedTop = getScrollY();
555 int listUnfadedBottom = listUnfadedTop + height;
556 final int fadingEdge = getVerticalFadingEdgeLength();
557
558 if (showingTopFadingEdge()) {
559 // leave room for top fading edge as long as rect isn't at very top
560 if ((mSelectedPosition > 0) || (rectTopWithinChild > fadingEdge)) {
561 listUnfadedTop += fadingEdge;
562 }
563 }
564
565 int childCount = getChildCount();
566 int bottomOfBottomChild = getChildAt(childCount - 1).getBottom();
567
568 if (showingBottomFadingEdge()) {
569 // leave room for bottom fading edge as long as rect isn't at very bottom
570 if ((mSelectedPosition < mItemCount - 1)
571 || (rect.bottom < (bottomOfBottomChild - fadingEdge))) {
572 listUnfadedBottom -= fadingEdge;
573 }
574 }
575
576 int scrollYDelta = 0;
577
578 if (rect.bottom > listUnfadedBottom && rect.top > listUnfadedTop) {
579 // need to MOVE DOWN to get it in view: move down just enough so
580 // that the entire rectangle is in view (or at least the first
581 // screen size chunk).
582
583 if (rect.height() > height) {
584 // just enough to get screen size chunk on
585 scrollYDelta += (rect.top - listUnfadedTop);
586 } else {
587 // get entire rect at bottom of screen
588 scrollYDelta += (rect.bottom - listUnfadedBottom);
589 }
590
591 // make sure we aren't scrolling beyond the end of our children
592 int distanceToBottom = bottomOfBottomChild - listUnfadedBottom;
593 scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
594 } else if (rect.top < listUnfadedTop && rect.bottom < listUnfadedBottom) {
595 // need to MOVE UP to get it in view: move up just enough so that
596 // entire rectangle is in view (or at least the first screen
597 // size chunk of it).
598
599 if (rect.height() > height) {
600 // screen size chunk
601 scrollYDelta -= (listUnfadedBottom - rect.bottom);
602 } else {
603 // entire rect at top
604 scrollYDelta -= (listUnfadedTop - rect.top);
605 }
606
607 // make sure we aren't scrolling any further than the top our children
608 int top = getChildAt(0).getTop();
609 int deltaToTop = top - listUnfadedTop;
610 scrollYDelta = Math.max(scrollYDelta, deltaToTop);
611 }
612
613 final boolean scroll = scrollYDelta != 0;
614 if (scroll) {
615 scrollListItemsBy(-scrollYDelta);
Dianne Hackborn079e2352010-10-18 17:02:43 -0700616 positionSelector(INVALID_POSITION, child);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 mSelectedTop = child.getTop();
618 invalidate();
619 }
620 return scroll;
621 }
622
623 /**
624 * {@inheritDoc}
625 */
626 @Override
627 void fillGap(boolean down) {
628 final int count = getChildCount();
629 if (down) {
Adam Powell8c3e0fc2010-11-17 15:13:51 -0800630 int paddingTop = 0;
631 if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) {
632 paddingTop = getListPaddingTop();
633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 final int startOffset = count > 0 ? getChildAt(count - 1).getBottom() + mDividerHeight :
Adam Powell8c3e0fc2010-11-17 15:13:51 -0800635 paddingTop;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 fillDown(mFirstPosition + count, startOffset);
637 correctTooHigh(getChildCount());
638 } else {
Adam Powell8c3e0fc2010-11-17 15:13:51 -0800639 int paddingBottom = 0;
640 if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) {
641 paddingBottom = getListPaddingBottom();
642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 final int startOffset = count > 0 ? getChildAt(0).getTop() - mDividerHeight :
Adam Powell8c3e0fc2010-11-17 15:13:51 -0800644 getHeight() - paddingBottom;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 fillUp(mFirstPosition - 1, startOffset);
646 correctTooLow(getChildCount());
647 }
648 }
649
650 /**
651 * Fills the list from pos down to the end of the list view.
652 *
653 * @param pos The first position to put in the list
654 *
655 * @param nextTop The location where the top of the item associated with pos
656 * should be drawn
657 *
658 * @return The view that is currently selected, if it happens to be in the
659 * range that we draw.
660 */
661 private View fillDown(int pos, int nextTop) {
662 View selectedView = null;
663
Adam Powell8c3e0fc2010-11-17 15:13:51 -0800664 int end = (mBottom - mTop);
665 if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) {
666 end -= mListPadding.bottom;
667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668
669 while (nextTop < end && pos < mItemCount) {
670 // is this the selected item?
671 boolean selected = pos == mSelectedPosition;
672 View child = makeAndAddView(pos, nextTop, true, mListPadding.left, selected);
673
674 nextTop = child.getBottom() + mDividerHeight;
675 if (selected) {
676 selectedView = child;
677 }
678 pos++;
679 }
680
681 return selectedView;
682 }
683
684 /**
685 * Fills the list from pos up to the top of the list view.
686 *
687 * @param pos The first position to put in the list
688 *
689 * @param nextBottom The location where the bottom of the item associated
690 * with pos should be drawn
691 *
692 * @return The view that is currently selected
693 */
694 private View fillUp(int pos, int nextBottom) {
695 View selectedView = null;
696
Adam Powell8c3e0fc2010-11-17 15:13:51 -0800697 int end = 0;
698 if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) {
699 end = mListPadding.top;
700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701
702 while (nextBottom > end && pos >= 0) {
703 // is this the selected item?
704 boolean selected = pos == mSelectedPosition;
705 View child = makeAndAddView(pos, nextBottom, false, mListPadding.left, selected);
706 nextBottom = child.getTop() - mDividerHeight;
707 if (selected) {
708 selectedView = child;
709 }
710 pos--;
711 }
712
713 mFirstPosition = pos + 1;
714
715 return selectedView;
716 }
717
718 /**
719 * Fills the list from top to bottom, starting with mFirstPosition
720 *
721 * @param nextTop The location where the top of the first item should be
722 * drawn
723 *
724 * @return The view that is currently selected
725 */
726 private View fillFromTop(int nextTop) {
727 mFirstPosition = Math.min(mFirstPosition, mSelectedPosition);
728 mFirstPosition = Math.min(mFirstPosition, mItemCount - 1);
729 if (mFirstPosition < 0) {
730 mFirstPosition = 0;
731 }
732 return fillDown(mFirstPosition, nextTop);
733 }
734
735
736 /**
737 * Put mSelectedPosition in the middle of the screen and then build up and
738 * down from there. This method forces mSelectedPosition to the center.
739 *
740 * @param childrenTop Top of the area in which children can be drawn, as
741 * measured in pixels
742 * @param childrenBottom Bottom of the area in which children can be drawn,
743 * as measured in pixels
744 * @return Currently selected view
745 */
746 private View fillFromMiddle(int childrenTop, int childrenBottom) {
747 int height = childrenBottom - childrenTop;
748
749 int position = reconcileSelectedPosition();
750
751 View sel = makeAndAddView(position, childrenTop, true,
752 mListPadding.left, true);
753 mFirstPosition = position;
754
755 int selHeight = sel.getMeasuredHeight();
756 if (selHeight <= height) {
757 sel.offsetTopAndBottom((height - selHeight) / 2);
758 }
759
760 fillAboveAndBelow(sel, position);
761
762 if (!mStackFromBottom) {
763 correctTooHigh(getChildCount());
764 } else {
765 correctTooLow(getChildCount());
766 }
767
768 return sel;
769 }
770
771 /**
772 * Once the selected view as been placed, fill up the visible area above and
773 * below it.
774 *
775 * @param sel The selected view
776 * @param position The position corresponding to sel
777 */
778 private void fillAboveAndBelow(View sel, int position) {
779 final int dividerHeight = mDividerHeight;
780 if (!mStackFromBottom) {
781 fillUp(position - 1, sel.getTop() - dividerHeight);
782 adjustViewsUpOrDown();
783 fillDown(position + 1, sel.getBottom() + dividerHeight);
784 } else {
785 fillDown(position + 1, sel.getBottom() + dividerHeight);
786 adjustViewsUpOrDown();
787 fillUp(position - 1, sel.getTop() - dividerHeight);
788 }
789 }
790
791
792 /**
793 * Fills the grid based on positioning the new selection at a specific
794 * location. The selection may be moved so that it does not intersect the
795 * faded edges. The grid is then filled upwards and downwards from there.
796 *
797 * @param selectedTop Where the selected item should be
798 * @param childrenTop Where to start drawing children
799 * @param childrenBottom Last pixel where children can be drawn
800 * @return The view that currently has selection
801 */
802 private View fillFromSelection(int selectedTop, int childrenTop, int childrenBottom) {
803 int fadingEdgeLength = getVerticalFadingEdgeLength();
804 final int selectedPosition = mSelectedPosition;
805
806 View sel;
807
808 final int topSelectionPixel = getTopSelectionPixel(childrenTop, fadingEdgeLength,
809 selectedPosition);
810 final int bottomSelectionPixel = getBottomSelectionPixel(childrenBottom, fadingEdgeLength,
811 selectedPosition);
812
813 sel = makeAndAddView(selectedPosition, selectedTop, true, mListPadding.left, true);
814
815
816 // Some of the newly selected item extends below the bottom of the list
817 if (sel.getBottom() > bottomSelectionPixel) {
818 // Find space available above the selection into which we can scroll
819 // upwards
820 final int spaceAbove = sel.getTop() - topSelectionPixel;
821
822 // Find space required to bring the bottom of the selected item
823 // fully into view
824 final int spaceBelow = sel.getBottom() - bottomSelectionPixel;
825 final int offset = Math.min(spaceAbove, spaceBelow);
826
827 // Now offset the selected item to get it into view
828 sel.offsetTopAndBottom(-offset);
829 } else if (sel.getTop() < topSelectionPixel) {
830 // Find space required to bring the top of the selected item fully
831 // into view
832 final int spaceAbove = topSelectionPixel - sel.getTop();
833
834 // Find space available below the selection into which we can scroll
835 // downwards
836 final int spaceBelow = bottomSelectionPixel - sel.getBottom();
837 final int offset = Math.min(spaceAbove, spaceBelow);
838
839 // Offset the selected item to get it into view
840 sel.offsetTopAndBottom(offset);
841 }
842
843 // Fill in views above and below
844 fillAboveAndBelow(sel, selectedPosition);
845
846 if (!mStackFromBottom) {
847 correctTooHigh(getChildCount());
848 } else {
849 correctTooLow(getChildCount());
850 }
851
852 return sel;
853 }
854
855 /**
856 * Calculate the bottom-most pixel we can draw the selection into
857 *
858 * @param childrenBottom Bottom pixel were children can be drawn
859 * @param fadingEdgeLength Length of the fading edge in pixels, if present
860 * @param selectedPosition The position that will be selected
861 * @return The bottom-most pixel we can draw the selection into
862 */
863 private int getBottomSelectionPixel(int childrenBottom, int fadingEdgeLength,
864 int selectedPosition) {
865 int bottomSelectionPixel = childrenBottom;
866 if (selectedPosition != mItemCount - 1) {
867 bottomSelectionPixel -= fadingEdgeLength;
868 }
869 return bottomSelectionPixel;
870 }
871
872 /**
873 * Calculate the top-most pixel we can draw the selection into
874 *
875 * @param childrenTop Top pixel were children can be drawn
876 * @param fadingEdgeLength Length of the fading edge in pixels, if present
877 * @param selectedPosition The position that will be selected
878 * @return The top-most pixel we can draw the selection into
879 */
880 private int getTopSelectionPixel(int childrenTop, int fadingEdgeLength, int selectedPosition) {
881 // first pixel we can draw the selection into
882 int topSelectionPixel = childrenTop;
883 if (selectedPosition > 0) {
884 topSelectionPixel += fadingEdgeLength;
885 }
886 return topSelectionPixel;
887 }
888
Winson Chung499cb9f2010-07-16 11:18:17 -0700889 /**
890 * Smoothly scroll to the specified adapter position. The view will
891 * scroll such that the indicated position is displayed.
892 * @param position Scroll to this adapter position.
893 */
894 @android.view.RemotableViewMethod
895 public void smoothScrollToPosition(int position) {
896 super.smoothScrollToPosition(position);
897 }
898
899 /**
900 * Smoothly scroll to the specified adapter position offset. The view will
901 * scroll such that the indicated position is displayed.
902 * @param offset The amount to offset from the adapter position to scroll to.
903 */
904 @android.view.RemotableViewMethod
905 public void smoothScrollByOffset(int offset) {
906 super.smoothScrollByOffset(offset);
907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908
909 /**
910 * Fills the list based on positioning the new selection relative to the old
911 * selection. The new selection will be placed at, above, or below the
912 * location of the new selection depending on how the selection is moving.
913 * The selection will then be pinned to the visible part of the screen,
914 * excluding the edges that are faded. The list is then filled upwards and
915 * downwards from there.
916 *
917 * @param oldSel The old selected view. Useful for trying to put the new
918 * selection in the same place
919 * @param newSel The view that is to become selected. Useful for trying to
920 * put the new selection in the same place
921 * @param delta Which way we are moving
922 * @param childrenTop Where to start drawing children
923 * @param childrenBottom Last pixel where children can be drawn
924 * @return The view that currently has selection
925 */
926 private View moveSelection(View oldSel, View newSel, int delta, int childrenTop,
927 int childrenBottom) {
928 int fadingEdgeLength = getVerticalFadingEdgeLength();
929 final int selectedPosition = mSelectedPosition;
930
931 View sel;
932
933 final int topSelectionPixel = getTopSelectionPixel(childrenTop, fadingEdgeLength,
934 selectedPosition);
935 final int bottomSelectionPixel = getBottomSelectionPixel(childrenTop, fadingEdgeLength,
936 selectedPosition);
937
938 if (delta > 0) {
939 /*
940 * Case 1: Scrolling down.
941 */
942
943 /*
944 * Before After
945 * | | | |
946 * +-------+ +-------+
947 * | A | | A |
948 * | 1 | => +-------+
949 * +-------+ | B |
950 * | B | | 2 |
951 * +-------+ +-------+
952 * | | | |
953 *
954 * Try to keep the top of the previously selected item where it was.
955 * oldSel = A
956 * sel = B
957 */
958
959 // Put oldSel (A) where it belongs
960 oldSel = makeAndAddView(selectedPosition - 1, oldSel.getTop(), true,
961 mListPadding.left, false);
962
963 final int dividerHeight = mDividerHeight;
964
965 // Now put the new selection (B) below that
966 sel = makeAndAddView(selectedPosition, oldSel.getBottom() + dividerHeight, true,
967 mListPadding.left, true);
968
969 // Some of the newly selected item extends below the bottom of the list
970 if (sel.getBottom() > bottomSelectionPixel) {
971
972 // Find space available above the selection into which we can scroll upwards
973 int spaceAbove = sel.getTop() - topSelectionPixel;
974
975 // Find space required to bring the bottom of the selected item fully into view
976 int spaceBelow = sel.getBottom() - bottomSelectionPixel;
977
978 // Don't scroll more than half the height of the list
979 int halfVerticalSpace = (childrenBottom - childrenTop) / 2;
980 int offset = Math.min(spaceAbove, spaceBelow);
981 offset = Math.min(offset, halfVerticalSpace);
982
983 // We placed oldSel, so offset that item
984 oldSel.offsetTopAndBottom(-offset);
985 // Now offset the selected item to get it into view
986 sel.offsetTopAndBottom(-offset);
987 }
988
989 // Fill in views above and below
990 if (!mStackFromBottom) {
991 fillUp(mSelectedPosition - 2, sel.getTop() - dividerHeight);
992 adjustViewsUpOrDown();
993 fillDown(mSelectedPosition + 1, sel.getBottom() + dividerHeight);
994 } else {
995 fillDown(mSelectedPosition + 1, sel.getBottom() + dividerHeight);
996 adjustViewsUpOrDown();
997 fillUp(mSelectedPosition - 2, sel.getTop() - dividerHeight);
998 }
999 } else if (delta < 0) {
1000 /*
1001 * Case 2: Scrolling up.
1002 */
1003
1004 /*
1005 * Before After
1006 * | | | |
1007 * +-------+ +-------+
1008 * | A | | A |
1009 * +-------+ => | 1 |
1010 * | B | +-------+
1011 * | 2 | | B |
1012 * +-------+ +-------+
1013 * | | | |
1014 *
1015 * Try to keep the top of the item about to become selected where it was.
1016 * newSel = A
1017 * olSel = B
1018 */
1019
1020 if (newSel != null) {
1021 // Try to position the top of newSel (A) where it was before it was selected
1022 sel = makeAndAddView(selectedPosition, newSel.getTop(), true, mListPadding.left,
1023 true);
1024 } else {
1025 // If (A) was not on screen and so did not have a view, position
1026 // it above the oldSel (B)
1027 sel = makeAndAddView(selectedPosition, oldSel.getTop(), false, mListPadding.left,
1028 true);
1029 }
1030
1031 // Some of the newly selected item extends above the top of the list
1032 if (sel.getTop() < topSelectionPixel) {
1033 // Find space required to bring the top of the selected item fully into view
1034 int spaceAbove = topSelectionPixel - sel.getTop();
1035
1036 // Find space available below the selection into which we can scroll downwards
1037 int spaceBelow = bottomSelectionPixel - sel.getBottom();
1038
1039 // Don't scroll more than half the height of the list
1040 int halfVerticalSpace = (childrenBottom - childrenTop) / 2;
1041 int offset = Math.min(spaceAbove, spaceBelow);
1042 offset = Math.min(offset, halfVerticalSpace);
1043
1044 // Offset the selected item to get it into view
1045 sel.offsetTopAndBottom(offset);
1046 }
1047
1048 // Fill in views above and below
1049 fillAboveAndBelow(sel, selectedPosition);
1050 } else {
1051
1052 int oldTop = oldSel.getTop();
1053
1054 /*
1055 * Case 3: Staying still
1056 */
1057 sel = makeAndAddView(selectedPosition, oldTop, true, mListPadding.left, true);
1058
1059 // We're staying still...
1060 if (oldTop < childrenTop) {
1061 // ... but the top of the old selection was off screen.
1062 // (This can happen if the data changes size out from under us)
1063 int newBottom = sel.getBottom();
1064 if (newBottom < childrenTop + 20) {
1065 // Not enough visible -- bring it onscreen
1066 sel.offsetTopAndBottom(childrenTop - sel.getTop());
1067 }
1068 }
1069
1070 // Fill in views above and below
1071 fillAboveAndBelow(sel, selectedPosition);
1072 }
1073
1074 return sel;
1075 }
1076
Adam Powell9bf3c122010-02-26 11:32:07 -08001077 private class FocusSelector implements Runnable {
1078 private int mPosition;
1079 private int mPositionTop;
1080
1081 public FocusSelector setup(int position, int top) {
1082 mPosition = position;
1083 mPositionTop = top;
1084 return this;
1085 }
1086
1087 public void run() {
1088 setSelectionFromTop(mPosition, mPositionTop);
1089 }
1090 }
1091
1092 @Override
1093 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1094 if (getChildCount() > 0) {
1095 View focusedChild = getFocusedChild();
1096 if (focusedChild != null) {
1097 final int childPosition = mFirstPosition + indexOfChild(focusedChild);
1098 final int childBottom = focusedChild.getBottom();
1099 final int offset = Math.max(0, childBottom - (h - mPaddingTop));
1100 final int top = focusedChild.getTop() - offset;
1101 if (mFocusSelector == null) {
1102 mFocusSelector = new FocusSelector();
1103 }
1104 post(mFocusSelector.setup(childPosition, top));
1105 }
1106 }
1107 super.onSizeChanged(w, h, oldw, oldh);
1108 }
1109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 @Override
1111 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
1112 // Sets up mListPadding
1113 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
1114
1115 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
1116 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
1117 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
1118 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
1119
1120 int childWidth = 0;
1121 int childHeight = 0;
Dianne Hackborn189ee182010-12-02 21:48:53 -08001122 int childState = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123
1124 mItemCount = mAdapter == null ? 0 : mAdapter.getCount();
1125 if (mItemCount > 0 && (widthMode == MeasureSpec.UNSPECIFIED ||
1126 heightMode == MeasureSpec.UNSPECIFIED)) {
Romain Guy21875052010-01-06 18:48:08 -08001127 final View child = obtainView(0, mIsScrap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128
1129 measureScrapChild(child, 0, widthMeasureSpec);
1130
1131 childWidth = child.getMeasuredWidth();
1132 childHeight = child.getMeasuredHeight();
Dianne Hackborn189ee182010-12-02 21:48:53 -08001133 childState = combineMeasuredStates(childState, child.getMeasuredState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134
Romain Guy9c3184cc2010-02-25 17:32:54 -08001135 if (recycleOnMeasure() && mRecycler.shouldRecycleViewType(
1136 ((LayoutParams) child.getLayoutParams()).viewType)) {
Dianne Hackborn079e2352010-10-18 17:02:43 -07001137 mRecycler.addScrapView(child, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 }
1139 }
1140
1141 if (widthMode == MeasureSpec.UNSPECIFIED) {
1142 widthSize = mListPadding.left + mListPadding.right + childWidth +
1143 getVerticalScrollbarWidth();
Dianne Hackborn189ee182010-12-02 21:48:53 -08001144 } else {
1145 widthSize |= (childState&MEASURED_STATE_MASK);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 }
1147
1148 if (heightMode == MeasureSpec.UNSPECIFIED) {
1149 heightSize = mListPadding.top + mListPadding.bottom + childHeight +
1150 getVerticalFadingEdgeLength() * 2;
1151 }
1152
1153 if (heightMode == MeasureSpec.AT_MOST) {
1154 // TODO: after first layout we should maybe start at the first visible position, not 0
1155 heightSize = measureHeightOfChildren(widthMeasureSpec, 0, NO_POSITION, heightSize, -1);
1156 }
1157
Dianne Hackborn189ee182010-12-02 21:48:53 -08001158 setMeasuredDimension(widthSize , heightSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 mWidthMeasureSpec = widthMeasureSpec;
1160 }
1161
1162 private void measureScrapChild(View child, int position, int widthMeasureSpec) {
1163 LayoutParams p = (LayoutParams) child.getLayoutParams();
1164 if (p == null) {
Romain Guy980a9382010-01-08 15:06:28 -08001165 p = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 ViewGroup.LayoutParams.WRAP_CONTENT, 0);
The Android Open Source Project4df24232009-03-05 14:34:35 -08001167 child.setLayoutParams(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 }
1169 p.viewType = mAdapter.getItemViewType(position);
Romain Guy0bf88592010-03-02 13:38:44 -08001170 p.forceAdd = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171
1172 int childWidthSpec = ViewGroup.getChildMeasureSpec(widthMeasureSpec,
1173 mListPadding.left + mListPadding.right, p.width);
1174 int lpHeight = p.height;
1175 int childHeightSpec;
1176 if (lpHeight > 0) {
1177 childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
1178 } else {
1179 childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1180 }
1181 child.measure(childWidthSpec, childHeightSpec);
1182 }
1183
1184 /**
1185 * @return True to recycle the views used to measure this ListView in
1186 * UNSPECIFIED/AT_MOST modes, false otherwise.
1187 * @hide
1188 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07001189 @ViewDebug.ExportedProperty(category = "list")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 protected boolean recycleOnMeasure() {
1191 return true;
1192 }
1193
1194 /**
1195 * Measures the height of the given range of children (inclusive) and
1196 * returns the height with this ListView's padding and divider heights
1197 * included. If maxHeight is provided, the measuring will stop when the
1198 * current height reaches maxHeight.
1199 *
1200 * @param widthMeasureSpec The width measure spec to be given to a child's
1201 * {@link View#measure(int, int)}.
1202 * @param startPosition The position of the first child to be shown.
1203 * @param endPosition The (inclusive) position of the last child to be
1204 * shown. Specify {@link #NO_POSITION} if the last child should be
1205 * the last available child from the adapter.
1206 * @param maxHeight The maximum height that will be returned (if all the
1207 * children don't fit in this value, this value will be
1208 * returned).
1209 * @param disallowPartialChildPosition In general, whether the returned
1210 * height should only contain entire children. This is more
1211 * powerful--it is the first inclusive position at which partial
1212 * children will not be allowed. Example: it looks nice to have
1213 * at least 3 completely visible children, and in portrait this
1214 * will most likely fit; but in landscape there could be times
1215 * when even 2 children can not be completely shown, so a value
1216 * of 2 (remember, inclusive) would be good (assuming
1217 * startPosition is 0).
1218 * @return The height of this ListView with the given children.
1219 */
1220 final int measureHeightOfChildren(int widthMeasureSpec, int startPosition, int endPosition,
1221 final int maxHeight, int disallowPartialChildPosition) {
1222
1223 final ListAdapter adapter = mAdapter;
1224 if (adapter == null) {
1225 return mListPadding.top + mListPadding.bottom;
1226 }
1227
1228 // Include the padding of the list
1229 int returnedHeight = mListPadding.top + mListPadding.bottom;
1230 final int dividerHeight = ((mDividerHeight > 0) && mDivider != null) ? mDividerHeight : 0;
1231 // The previous height value that was less than maxHeight and contained
1232 // no partial children
1233 int prevHeightWithoutPartialChild = 0;
1234 int i;
1235 View child;
1236
1237 // mItemCount - 1 since endPosition parameter is inclusive
1238 endPosition = (endPosition == NO_POSITION) ? adapter.getCount() - 1 : endPosition;
1239 final AbsListView.RecycleBin recycleBin = mRecycler;
1240 final boolean recyle = recycleOnMeasure();
Romain Guy21875052010-01-06 18:48:08 -08001241 final boolean[] isScrap = mIsScrap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242
1243 for (i = startPosition; i <= endPosition; ++i) {
Romain Guy21875052010-01-06 18:48:08 -08001244 child = obtainView(i, isScrap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245
1246 measureScrapChild(child, i, widthMeasureSpec);
1247
1248 if (i > 0) {
1249 // Count the divider for all but one child
1250 returnedHeight += dividerHeight;
1251 }
1252
1253 // Recycle the view before we possibly return from the method
Romain Guy9c3184cc2010-02-25 17:32:54 -08001254 if (recyle && recycleBin.shouldRecycleViewType(
1255 ((LayoutParams) child.getLayoutParams()).viewType)) {
Dianne Hackborn079e2352010-10-18 17:02:43 -07001256 recycleBin.addScrapView(child, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 }
1258
1259 returnedHeight += child.getMeasuredHeight();
1260
1261 if (returnedHeight >= maxHeight) {
1262 // We went over, figure out which height to return. If returnedHeight > maxHeight,
1263 // then the i'th position did not fit completely.
1264 return (disallowPartialChildPosition >= 0) // Disallowing is enabled (> -1)
1265 && (i > disallowPartialChildPosition) // We've past the min pos
1266 && (prevHeightWithoutPartialChild > 0) // We have a prev height
1267 && (returnedHeight != maxHeight) // i'th child did not fit completely
1268 ? prevHeightWithoutPartialChild
1269 : maxHeight;
1270 }
1271
1272 if ((disallowPartialChildPosition >= 0) && (i >= disallowPartialChildPosition)) {
1273 prevHeightWithoutPartialChild = returnedHeight;
1274 }
1275 }
1276
1277 // At this point, we went through the range of children, and they each
1278 // completely fit, so return the returnedHeight
1279 return returnedHeight;
1280 }
1281
1282 @Override
1283 int findMotionRow(int y) {
1284 int childCount = getChildCount();
1285 if (childCount > 0) {
Adam Powell84222e02010-03-11 13:42:57 -08001286 if (!mStackFromBottom) {
1287 for (int i = 0; i < childCount; i++) {
1288 View v = getChildAt(i);
1289 if (y <= v.getBottom()) {
1290 return mFirstPosition + i;
1291 }
1292 }
1293 } else {
1294 for (int i = childCount - 1; i >= 0; i--) {
1295 View v = getChildAt(i);
1296 if (y >= v.getTop()) {
1297 return mFirstPosition + i;
1298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 }
1300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 }
1302 return INVALID_POSITION;
1303 }
1304
1305 /**
1306 * Put a specific item at a specific location on the screen and then build
1307 * up and down from there.
1308 *
1309 * @param position The reference view to use as the starting point
1310 * @param top Pixel offset from the top of this view to the top of the
1311 * reference view.
1312 *
1313 * @return The selected view, or null if the selected view is outside the
1314 * visible area.
1315 */
1316 private View fillSpecific(int position, int top) {
1317 boolean tempIsSelected = position == mSelectedPosition;
1318 View temp = makeAndAddView(position, top, true, mListPadding.left, tempIsSelected);
1319 // Possibly changed again in fillUp if we add rows above this one.
1320 mFirstPosition = position;
1321
1322 View above;
1323 View below;
1324
1325 final int dividerHeight = mDividerHeight;
1326 if (!mStackFromBottom) {
1327 above = fillUp(position - 1, temp.getTop() - dividerHeight);
1328 // This will correct for the top of the first view not touching the top of the list
1329 adjustViewsUpOrDown();
1330 below = fillDown(position + 1, temp.getBottom() + dividerHeight);
1331 int childCount = getChildCount();
1332 if (childCount > 0) {
1333 correctTooHigh(childCount);
1334 }
1335 } else {
1336 below = fillDown(position + 1, temp.getBottom() + dividerHeight);
1337 // This will correct for the bottom of the last view not touching the bottom of the list
1338 adjustViewsUpOrDown();
1339 above = fillUp(position - 1, temp.getTop() - dividerHeight);
1340 int childCount = getChildCount();
1341 if (childCount > 0) {
1342 correctTooLow(childCount);
1343 }
1344 }
1345
1346 if (tempIsSelected) {
1347 return temp;
1348 } else if (above != null) {
1349 return above;
1350 } else {
1351 return below;
1352 }
1353 }
1354
1355 /**
1356 * Check if we have dragged the bottom of the list too high (we have pushed the
1357 * top element off the top of the screen when we did not need to). Correct by sliding
1358 * everything back down.
1359 *
1360 * @param childCount Number of children
1361 */
1362 private void correctTooHigh(int childCount) {
1363 // First see if the last item is visible. If it is not, it is OK for the
1364 // top of the list to be pushed up.
1365 int lastPosition = mFirstPosition + childCount - 1;
1366 if (lastPosition == mItemCount - 1 && childCount > 0) {
1367
1368 // Get the last child ...
1369 final View lastChild = getChildAt(childCount - 1);
1370
1371 // ... and its bottom edge
1372 final int lastBottom = lastChild.getBottom();
1373
1374 // This is bottom of our drawable area
1375 final int end = (mBottom - mTop) - mListPadding.bottom;
1376
1377 // This is how far the bottom edge of the last view is from the bottom of the
1378 // drawable area
1379 int bottomOffset = end - lastBottom;
1380 View firstChild = getChildAt(0);
1381 final int firstTop = firstChild.getTop();
1382
1383 // Make sure we are 1) Too high, and 2) Either there are more rows above the
1384 // first row or the first row is scrolled off the top of the drawable area
1385 if (bottomOffset > 0 && (mFirstPosition > 0 || firstTop < mListPadding.top)) {
1386 if (mFirstPosition == 0) {
1387 // Don't pull the top too far down
1388 bottomOffset = Math.min(bottomOffset, mListPadding.top - firstTop);
1389 }
1390 // Move everything down
1391 offsetChildrenTopAndBottom(bottomOffset);
1392 if (mFirstPosition > 0) {
1393 // Fill the gap that was opened above mFirstPosition with more rows, if
1394 // possible
1395 fillUp(mFirstPosition - 1, firstChild.getTop() - mDividerHeight);
1396 // Close up the remaining gap
1397 adjustViewsUpOrDown();
1398 }
1399
1400 }
1401 }
1402 }
1403
1404 /**
1405 * Check if we have dragged the bottom of the list too low (we have pushed the
1406 * bottom element off the bottom of the screen when we did not need to). Correct by sliding
1407 * everything back up.
1408 *
1409 * @param childCount Number of children
1410 */
1411 private void correctTooLow(int childCount) {
1412 // First see if the first item is visible. If it is not, it is OK for the
1413 // bottom of the list to be pushed down.
1414 if (mFirstPosition == 0 && childCount > 0) {
1415
1416 // Get the first child ...
1417 final View firstChild = getChildAt(0);
1418
1419 // ... and its top edge
1420 final int firstTop = firstChild.getTop();
1421
1422 // This is top of our drawable area
1423 final int start = mListPadding.top;
1424
1425 // This is bottom of our drawable area
1426 final int end = (mBottom - mTop) - mListPadding.bottom;
1427
1428 // This is how far the top edge of the first view is from the top of the
1429 // drawable area
1430 int topOffset = firstTop - start;
1431 View lastChild = getChildAt(childCount - 1);
1432 final int lastBottom = lastChild.getBottom();
1433 int lastPosition = mFirstPosition + childCount - 1;
1434
1435 // Make sure we are 1) Too low, and 2) Either there are more rows below the
1436 // last row or the last row is scrolled off the bottom of the drawable area
Romain Guy6198ae82009-08-31 17:45:55 -07001437 if (topOffset > 0) {
1438 if (lastPosition < mItemCount - 1 || lastBottom > end) {
1439 if (lastPosition == mItemCount - 1) {
1440 // Don't pull the bottom too far up
1441 topOffset = Math.min(topOffset, lastBottom - end);
1442 }
1443 // Move everything up
1444 offsetChildrenTopAndBottom(-topOffset);
1445 if (lastPosition < mItemCount - 1) {
1446 // Fill the gap that was opened below the last position with more rows, if
1447 // possible
1448 fillDown(lastPosition + 1, lastChild.getBottom() + mDividerHeight);
1449 // Close up the remaining gap
1450 adjustViewsUpOrDown();
1451 }
1452 } else if (lastPosition == mItemCount - 1) {
1453 adjustViewsUpOrDown();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 }
1455 }
1456 }
1457 }
1458
1459 @Override
1460 protected void layoutChildren() {
1461 final boolean blockLayoutRequests = mBlockLayoutRequests;
1462 if (!blockLayoutRequests) {
1463 mBlockLayoutRequests = true;
The Android Open Source Project4df24232009-03-05 14:34:35 -08001464 } else {
1465 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 }
1467
1468 try {
1469 super.layoutChildren();
1470
1471 invalidate();
1472
1473 if (mAdapter == null) {
1474 resetList();
1475 invokeOnItemScrollListener();
1476 return;
1477 }
1478
1479 int childrenTop = mListPadding.top;
1480 int childrenBottom = mBottom - mTop - mListPadding.bottom;
1481
1482 int childCount = getChildCount();
Romain Guyead0d4d2009-12-08 17:33:53 -08001483 int index = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 int delta = 0;
1485
1486 View sel;
1487 View oldSel = null;
1488 View oldFirst = null;
1489 View newSel = null;
1490
1491 View focusLayoutRestoreView = null;
1492
1493 // Remember stuff we will need down below
1494 switch (mLayoutMode) {
1495 case LAYOUT_SET_SELECTION:
1496 index = mNextSelectedPosition - mFirstPosition;
1497 if (index >= 0 && index < childCount) {
1498 newSel = getChildAt(index);
1499 }
1500 break;
1501 case LAYOUT_FORCE_TOP:
1502 case LAYOUT_FORCE_BOTTOM:
1503 case LAYOUT_SPECIFIC:
1504 case LAYOUT_SYNC:
1505 break;
1506 case LAYOUT_MOVE_SELECTION:
1507 default:
1508 // Remember the previously selected view
1509 index = mSelectedPosition - mFirstPosition;
1510 if (index >= 0 && index < childCount) {
1511 oldSel = getChildAt(index);
1512 }
1513
1514 // Remember the previous first child
1515 oldFirst = getChildAt(0);
1516
1517 if (mNextSelectedPosition >= 0) {
1518 delta = mNextSelectedPosition - mSelectedPosition;
1519 }
1520
1521 // Caution: newSel might be null
1522 newSel = getChildAt(index + delta);
1523 }
1524
1525
1526 boolean dataChanged = mDataChanged;
1527 if (dataChanged) {
1528 handleDataChanged();
1529 }
1530
1531 // Handle the empty set by removing all views that are visible
1532 // and calling it a day
1533 if (mItemCount == 0) {
1534 resetList();
1535 invokeOnItemScrollListener();
1536 return;
Romain Guyb45f1242009-03-24 21:30:00 -07001537 } else if (mItemCount != mAdapter.getCount()) {
1538 throw new IllegalStateException("The content of the adapter has changed but "
1539 + "ListView did not receive a notification. Make sure the content of "
1540 + "your adapter is not modified from a background thread, but only "
Owen Lin3940f2d2009-08-13 15:21:16 +08001541 + "from the UI thread. [in ListView(" + getId() + ", " + getClass()
1542 + ") with Adapter(" + mAdapter.getClass() + ")]");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 }
1544
1545 setSelectedPositionInt(mNextSelectedPosition);
1546
1547 // Pull all children into the RecycleBin.
1548 // These views will be reused if possible
1549 final int firstPosition = mFirstPosition;
1550 final RecycleBin recycleBin = mRecycler;
1551
1552 // reset the focus restoration
1553 View focusLayoutRestoreDirectChild = null;
1554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 // Don't put header or footer views into the Recycler. Those are
1556 // already cached in mHeaderViews;
1557 if (dataChanged) {
1558 for (int i = 0; i < childCount; i++) {
Dianne Hackborn079e2352010-10-18 17:02:43 -07001559 recycleBin.addScrapView(getChildAt(i), firstPosition+i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 if (ViewDebug.TRACE_RECYCLER) {
1561 ViewDebug.trace(getChildAt(i),
1562 ViewDebug.RecyclerTraceType.MOVE_TO_SCRAP_HEAP, index, i);
1563 }
1564 }
1565 } else {
1566 recycleBin.fillActiveViews(childCount, firstPosition);
1567 }
1568
1569 // take focus back to us temporarily to avoid the eventual
1570 // call to clear focus when removing the focused child below
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07001571 // from messing things up when ViewAncestor assigns focus back
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 // to someone else
1573 final View focusedChild = getFocusedChild();
1574 if (focusedChild != null) {
1575 // TODO: in some cases focusedChild.getParent() == null
1576
1577 // we can remember the focused view to restore after relayout if the
1578 // data hasn't changed, or if the focused position is a header or footer
1579 if (!dataChanged || isDirectChildHeaderOrFooter(focusedChild)) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08001580 focusLayoutRestoreDirectChild = focusedChild;
1581 // remember the specific view that had focus
1582 focusLayoutRestoreView = findFocus();
1583 if (focusLayoutRestoreView != null) {
1584 // tell it we are going to mess with it
1585 focusLayoutRestoreView.onStartTemporaryDetach();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 }
1587 }
1588 requestFocus();
1589 }
1590
1591 // Clear out old views
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 detachAllViewsFromParent();
1593
1594 switch (mLayoutMode) {
1595 case LAYOUT_SET_SELECTION:
1596 if (newSel != null) {
1597 sel = fillFromSelection(newSel.getTop(), childrenTop, childrenBottom);
1598 } else {
1599 sel = fillFromMiddle(childrenTop, childrenBottom);
1600 }
1601 break;
1602 case LAYOUT_SYNC:
1603 sel = fillSpecific(mSyncPosition, mSpecificTop);
1604 break;
1605 case LAYOUT_FORCE_BOTTOM:
1606 sel = fillUp(mItemCount - 1, childrenBottom);
1607 adjustViewsUpOrDown();
1608 break;
1609 case LAYOUT_FORCE_TOP:
1610 mFirstPosition = 0;
1611 sel = fillFromTop(childrenTop);
1612 adjustViewsUpOrDown();
1613 break;
1614 case LAYOUT_SPECIFIC:
1615 sel = fillSpecific(reconcileSelectedPosition(), mSpecificTop);
1616 break;
1617 case LAYOUT_MOVE_SELECTION:
1618 sel = moveSelection(oldSel, newSel, delta, childrenTop, childrenBottom);
1619 break;
1620 default:
1621 if (childCount == 0) {
1622 if (!mStackFromBottom) {
1623 final int position = lookForSelectablePosition(0, true);
1624 setSelectedPositionInt(position);
1625 sel = fillFromTop(childrenTop);
1626 } else {
1627 final int position = lookForSelectablePosition(mItemCount - 1, false);
1628 setSelectedPositionInt(position);
1629 sel = fillUp(mItemCount - 1, childrenBottom);
1630 }
1631 } else {
1632 if (mSelectedPosition >= 0 && mSelectedPosition < mItemCount) {
1633 sel = fillSpecific(mSelectedPosition,
1634 oldSel == null ? childrenTop : oldSel.getTop());
1635 } else if (mFirstPosition < mItemCount) {
1636 sel = fillSpecific(mFirstPosition,
1637 oldFirst == null ? childrenTop : oldFirst.getTop());
1638 } else {
1639 sel = fillSpecific(0, childrenTop);
1640 }
1641 }
1642 break;
1643 }
1644
1645 // Flush any cached views that did not get reused above
1646 recycleBin.scrapActiveViews();
1647
1648 if (sel != null) {
Romain Guy3616a412009-09-15 13:50:37 -07001649 // the current selected item should get focus if items
1650 // are focusable
1651 if (mItemsCanFocus && hasFocus() && !sel.hasFocus()) {
1652 final boolean focusWasTaken = (sel == focusLayoutRestoreDirectChild &&
1653 focusLayoutRestoreView.requestFocus()) || sel.requestFocus();
1654 if (!focusWasTaken) {
1655 // selected item didn't take focus, fine, but still want
1656 // to make sure something else outside of the selected view
1657 // has focus
1658 final View focused = getFocusedChild();
1659 if (focused != null) {
1660 focused.clearFocus();
1661 }
Dianne Hackborn079e2352010-10-18 17:02:43 -07001662 positionSelector(INVALID_POSITION, sel);
Romain Guy3616a412009-09-15 13:50:37 -07001663 } else {
1664 sel.setSelected(false);
1665 mSelectorRect.setEmpty();
1666 }
1667 } else {
Dianne Hackborn079e2352010-10-18 17:02:43 -07001668 positionSelector(INVALID_POSITION, sel);
Romain Guy3616a412009-09-15 13:50:37 -07001669 }
1670 mSelectedTop = sel.getTop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 } else {
Romain Guy3616a412009-09-15 13:50:37 -07001672 if (mTouchMode > TOUCH_MODE_DOWN && mTouchMode < TOUCH_MODE_SCROLL) {
1673 View child = getChildAt(mMotionPosition - mFirstPosition);
Dianne Hackborn079e2352010-10-18 17:02:43 -07001674 if (child != null) positionSelector(mMotionPosition, child);
Romain Guy3616a412009-09-15 13:50:37 -07001675 } else {
1676 mSelectedTop = 0;
1677 mSelectorRect.setEmpty();
1678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679
Romain Guy3616a412009-09-15 13:50:37 -07001680 // even if there is not selected position, we may need to restore
1681 // focus (i.e. something focusable in touch mode)
1682 if (hasFocus() && focusLayoutRestoreView != null) {
1683 focusLayoutRestoreView.requestFocus();
1684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 }
1686
1687 // tell focus view we are done mucking with it, if it is still in
1688 // our view hierarchy.
1689 if (focusLayoutRestoreView != null
1690 && focusLayoutRestoreView.getWindowToken() != null) {
1691 focusLayoutRestoreView.onFinishTemporaryDetach();
1692 }
1693
1694 mLayoutMode = LAYOUT_NORMAL;
1695 mDataChanged = false;
1696 mNeedSync = false;
1697 setNextSelectedPositionInt(mSelectedPosition);
1698
1699 updateScrollIndicators();
1700
1701 if (mItemCount > 0) {
1702 checkSelectionChanged();
1703 }
1704
1705 invokeOnItemScrollListener();
1706 } finally {
1707 if (!blockLayoutRequests) {
1708 mBlockLayoutRequests = false;
1709 }
1710 }
1711 }
1712
1713 /**
1714 * @param child a direct child of this list.
1715 * @return Whether child is a header or footer view.
1716 */
1717 private boolean isDirectChildHeaderOrFooter(View child) {
1718
1719 final ArrayList<FixedViewInfo> headers = mHeaderViewInfos;
1720 final int numHeaders = headers.size();
1721 for (int i = 0; i < numHeaders; i++) {
1722 if (child == headers.get(i).view) {
1723 return true;
1724 }
1725 }
1726 final ArrayList<FixedViewInfo> footers = mFooterViewInfos;
1727 final int numFooters = footers.size();
1728 for (int i = 0; i < numFooters; i++) {
1729 if (child == footers.get(i).view) {
1730 return true;
1731 }
1732 }
1733 return false;
1734 }
1735
1736 /**
1737 * Obtain the view and add it to our list of children. The view can be made
1738 * fresh, converted from an unused view, or used as is if it was in the
1739 * recycle bin.
1740 *
1741 * @param position Logical position in the list
1742 * @param y Top or bottom edge of the view to add
1743 * @param flow If flow is true, align top edge to y. If false, align bottom
1744 * edge to y.
1745 * @param childrenLeft Left edge where children should be positioned
1746 * @param selected Is this position selected?
1747 * @return View that was added
1748 */
1749 private View makeAndAddView(int position, int y, boolean flow, int childrenLeft,
1750 boolean selected) {
1751 View child;
1752
1753
1754 if (!mDataChanged) {
Dianne Hackborn079e2352010-10-18 17:02:43 -07001755 // Try to use an existing view for this position
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 child = mRecycler.getActiveView(position);
1757 if (child != null) {
1758 if (ViewDebug.TRACE_RECYCLER) {
1759 ViewDebug.trace(child, ViewDebug.RecyclerTraceType.RECYCLE_FROM_ACTIVE_HEAP,
1760 position, getChildCount());
1761 }
1762
1763 // Found it -- we're using an existing child
1764 // This just needs to be positioned
1765 setupChild(child, position, y, flow, childrenLeft, selected, true);
1766
1767 return child;
1768 }
1769 }
1770
1771 // Make a new view for this position, or convert an unused view if possible
Romain Guy21875052010-01-06 18:48:08 -08001772 child = obtainView(position, mIsScrap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773
1774 // This needs to be positioned and measured
Romain Guy21875052010-01-06 18:48:08 -08001775 setupChild(child, position, y, flow, childrenLeft, selected, mIsScrap[0]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776
1777 return child;
1778 }
1779
1780 /**
1781 * Add a view as a child and make sure it is measured (if necessary) and
1782 * positioned properly.
1783 *
1784 * @param child The view to add
1785 * @param position The position of this child
1786 * @param y The y position relative to which this view will be positioned
1787 * @param flowDown If true, align top edge to y. If false, align bottom
1788 * edge to y.
1789 * @param childrenLeft Left edge where children should be positioned
1790 * @param selected Is this position selected?
1791 * @param recycled Has this view been pulled from the recycle bin? If so it
1792 * does not need to be remeasured.
1793 */
1794 private void setupChild(View child, int position, int y, boolean flowDown, int childrenLeft,
1795 boolean selected, boolean recycled) {
1796 final boolean isSelected = selected && shouldShowSelector();
1797 final boolean updateChildSelected = isSelected != child.isSelected();
Romain Guy3616a412009-09-15 13:50:37 -07001798 final int mode = mTouchMode;
1799 final boolean isPressed = mode > TOUCH_MODE_DOWN && mode < TOUCH_MODE_SCROLL &&
1800 mMotionPosition == position;
1801 final boolean updateChildPressed = isPressed != child.isPressed();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 final boolean needToMeasure = !recycled || updateChildSelected || child.isLayoutRequested();
1803
1804 // Respect layout params that are already in the view. Otherwise make some up...
1805 // noinspection unchecked
1806 AbsListView.LayoutParams p = (AbsListView.LayoutParams) child.getLayoutParams();
1807 if (p == null) {
Romain Guy980a9382010-01-08 15:06:28 -08001808 p = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 ViewGroup.LayoutParams.WRAP_CONTENT, 0);
1810 }
1811 p.viewType = mAdapter.getItemViewType(position);
1812
Romain Guy0bf88592010-03-02 13:38:44 -08001813 if ((recycled && !p.forceAdd) || (p.recycledHeaderFooter &&
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001814 p.viewType == AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 attachViewToParent(child, flowDown ? -1 : 0, p);
1816 } else {
Romain Guy0bf88592010-03-02 13:38:44 -08001817 p.forceAdd = false;
The Android Open Source Project4df24232009-03-05 14:34:35 -08001818 if (p.viewType == AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER) {
1819 p.recycledHeaderFooter = true;
1820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 addViewInLayout(child, flowDown ? -1 : 0, p, true);
1822 }
1823
1824 if (updateChildSelected) {
1825 child.setSelected(isSelected);
1826 }
1827
Romain Guy3616a412009-09-15 13:50:37 -07001828 if (updateChildPressed) {
1829 child.setPressed(isPressed);
1830 }
1831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null) {
1833 if (child instanceof Checkable) {
1834 ((Checkable) child).setChecked(mCheckStates.get(position));
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07001835 } else if (getContext().getApplicationInfo().targetSdkVersion
1836 >= android.os.Build.VERSION_CODES.HONEYCOMB) {
1837 child.setActivated(mCheckStates.get(position));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 }
1839 }
1840
1841 if (needToMeasure) {
1842 int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
1843 mListPadding.left + mListPadding.right, p.width);
1844 int lpHeight = p.height;
1845 int childHeightSpec;
1846 if (lpHeight > 0) {
1847 childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
1848 } else {
1849 childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1850 }
1851 child.measure(childWidthSpec, childHeightSpec);
1852 } else {
1853 cleanupLayoutState(child);
1854 }
1855
1856 final int w = child.getMeasuredWidth();
1857 final int h = child.getMeasuredHeight();
1858 final int childTop = flowDown ? y : y - h;
1859
1860 if (needToMeasure) {
1861 final int childRight = childrenLeft + w;
1862 final int childBottom = childTop + h;
1863 child.layout(childrenLeft, childTop, childRight, childBottom);
1864 } else {
1865 child.offsetLeftAndRight(childrenLeft - child.getLeft());
1866 child.offsetTopAndBottom(childTop - child.getTop());
1867 }
1868
1869 if (mCachingStarted && !child.isDrawingCacheEnabled()) {
1870 child.setDrawingCacheEnabled(true);
1871 }
Dianne Hackborn079e2352010-10-18 17:02:43 -07001872
1873 if (recycled && (((AbsListView.LayoutParams)child.getLayoutParams()).scrappedFromPosition)
1874 != position) {
1875 child.jumpDrawablesToCurrentState();
1876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 }
1878
1879 @Override
1880 protected boolean canAnimate() {
1881 return super.canAnimate() && mItemCount > 0;
1882 }
1883
1884 /**
1885 * Sets the currently selected item. If in touch mode, the item will not be selected
1886 * but it will still be positioned appropriately. If the specified selection position
1887 * is less than 0, then the item at position 0 will be selected.
1888 *
1889 * @param position Index (starting at 0) of the data item to be selected.
1890 */
1891 @Override
1892 public void setSelection(int position) {
1893 setSelectionFromTop(position, 0);
1894 }
1895
1896 /**
1897 * Sets the selected item and positions the selection y pixels from the top edge
1898 * of the ListView. (If in touch mode, the item will not be selected but it will
1899 * still be positioned appropriately.)
1900 *
1901 * @param position Index (starting at 0) of the data item to be selected.
1902 * @param y The distance from the top edge of the ListView (plus padding) that the
1903 * item will be positioned.
1904 */
1905 public void setSelectionFromTop(int position, int y) {
1906 if (mAdapter == null) {
1907 return;
1908 }
1909
1910 if (!isInTouchMode()) {
1911 position = lookForSelectablePosition(position, true);
1912 if (position >= 0) {
1913 setNextSelectedPositionInt(position);
1914 }
1915 } else {
1916 mResurrectToPosition = position;
1917 }
1918
1919 if (position >= 0) {
1920 mLayoutMode = LAYOUT_SPECIFIC;
1921 mSpecificTop = mListPadding.top + y;
1922
1923 if (mNeedSync) {
1924 mSyncPosition = position;
1925 mSyncRowId = mAdapter.getItemId(position);
1926 }
1927
1928 requestLayout();
1929 }
1930 }
1931
1932 /**
1933 * Makes the item at the supplied position selected.
Mike Cleronf116bf82009-09-27 19:14:12 -07001934 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 * @param position the position of the item to select
1936 */
1937 @Override
1938 void setSelectionInt(int position) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 setNextSelectedPositionInt(position);
Mike Cleronf116bf82009-09-27 19:14:12 -07001940 boolean awakeScrollbars = false;
1941
1942 final int selectedPosition = mSelectedPosition;
1943
1944 if (selectedPosition >= 0) {
1945 if (position == selectedPosition - 1) {
1946 awakeScrollbars = true;
1947 } else if (position == selectedPosition + 1) {
1948 awakeScrollbars = true;
1949 }
1950 }
1951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 layoutChildren();
Mike Cleronf116bf82009-09-27 19:14:12 -07001953
1954 if (awakeScrollbars) {
1955 awakenScrollBars();
1956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 }
1958
1959 /**
1960 * Find a position that can be selected (i.e., is not a separator).
1961 *
1962 * @param position The starting position to look at.
1963 * @param lookDown Whether to look down for other positions.
1964 * @return The next selectable position starting at position and then searching either up or
1965 * down. Returns {@link #INVALID_POSITION} if nothing can be found.
1966 */
1967 @Override
1968 int lookForSelectablePosition(int position, boolean lookDown) {
1969 final ListAdapter adapter = mAdapter;
1970 if (adapter == null || isInTouchMode()) {
1971 return INVALID_POSITION;
1972 }
1973
1974 final int count = adapter.getCount();
1975 if (!mAreAllItemsSelectable) {
1976 if (lookDown) {
1977 position = Math.max(0, position);
1978 while (position < count && !adapter.isEnabled(position)) {
1979 position++;
1980 }
1981 } else {
1982 position = Math.min(position, count - 1);
1983 while (position >= 0 && !adapter.isEnabled(position)) {
1984 position--;
1985 }
1986 }
1987
1988 if (position < 0 || position >= count) {
1989 return INVALID_POSITION;
1990 }
1991 return position;
1992 } else {
1993 if (position < 0 || position >= count) {
1994 return INVALID_POSITION;
1995 }
1996 return position;
1997 }
1998 }
1999
svetoslavganov75986cf2009-05-14 22:28:01 -07002000 @Override
Svetoslav Ganov30401322011-05-12 18:53:45 -07002001 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2002 super.onInitializeAccessibilityEvent(event);
svetoslavganov75986cf2009-05-14 22:28:01 -07002003
Amith Yamasanid296faf2009-06-04 12:11:25 -07002004 // If the item count is less than 15 then subtract disabled items from the count and
2005 // position. Otherwise ignore disabled items.
Svetoslav Ganov736c2752011-04-22 18:30:36 -07002006 int itemCount = 0;
2007 int currentItemIndex = getSelectedItemPosition();
svetoslavganov75986cf2009-05-14 22:28:01 -07002008
Svetoslav Ganov736c2752011-04-22 18:30:36 -07002009 ListAdapter adapter = getAdapter();
2010 if (adapter != null) {
2011 final int count = adapter.getCount();
Svetoslav Ganov887e1a12011-04-29 15:09:28 -07002012 for (int i = 0; i < count; i++) {
2013 if (adapter.isEnabled(i)) {
2014 itemCount++;
2015 } else if (i <= currentItemIndex) {
2016 currentItemIndex--;
svetoslavganov75986cf2009-05-14 22:28:01 -07002017 }
2018 }
svetoslavganov75986cf2009-05-14 22:28:01 -07002019 }
2020
Svetoslav Ganov736c2752011-04-22 18:30:36 -07002021 event.setItemCount(itemCount);
2022 event.setCurrentItemIndex(currentItemIndex);
svetoslavganov75986cf2009-05-14 22:28:01 -07002023 }
2024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 /**
2026 * setSelectionAfterHeaderView set the selection to be the first list item
2027 * after the header views.
2028 */
2029 public void setSelectionAfterHeaderView() {
2030 final int count = mHeaderViewInfos.size();
2031 if (count > 0) {
2032 mNextSelectedPosition = 0;
2033 return;
2034 }
2035
2036 if (mAdapter != null) {
2037 setSelection(count);
2038 } else {
2039 mNextSelectedPosition = count;
2040 mLayoutMode = LAYOUT_SET_SELECTION;
2041 }
2042
2043 }
2044
2045 @Override
2046 public boolean dispatchKeyEvent(KeyEvent event) {
2047 // Dispatch in the normal way
2048 boolean handled = super.dispatchKeyEvent(event);
2049 if (!handled) {
2050 // If we didn't handle it...
2051 View focused = getFocusedChild();
2052 if (focused != null && event.getAction() == KeyEvent.ACTION_DOWN) {
2053 // ... and our focused child didn't handle it
2054 // ... give it to ourselves so we can scroll if necessary
2055 handled = onKeyDown(event.getKeyCode(), event);
2056 }
2057 }
2058 return handled;
2059 }
2060
2061 @Override
2062 public boolean onKeyDown(int keyCode, KeyEvent event) {
2063 return commonKey(keyCode, 1, event);
2064 }
2065
2066 @Override
2067 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
2068 return commonKey(keyCode, repeatCount, event);
2069 }
2070
2071 @Override
2072 public boolean onKeyUp(int keyCode, KeyEvent event) {
2073 return commonKey(keyCode, 1, event);
2074 }
2075
2076 private boolean commonKey(int keyCode, int count, KeyEvent event) {
2077 if (mAdapter == null) {
2078 return false;
2079 }
2080
2081 if (mDataChanged) {
2082 layoutChildren();
2083 }
2084
2085 boolean handled = false;
2086 int action = event.getAction();
2087
2088 if (action != KeyEvent.ACTION_UP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 switch (keyCode) {
2090 case KeyEvent.KEYCODE_DPAD_UP:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002091 if (event.hasNoModifiers()) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002092 handled = resurrectSelectionIfNeeded();
2093 if (!handled) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002094 while (count-- > 0) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002095 if (arrowScroll(FOCUS_UP)) {
2096 handled = true;
2097 } else {
2098 break;
2099 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002102 } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002103 handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_UP);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 }
2105 break;
2106
2107 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002108 if (event.hasNoModifiers()) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002109 handled = resurrectSelectionIfNeeded();
2110 if (!handled) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002111 while (count-- > 0) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002112 if (arrowScroll(FOCUS_DOWN)) {
2113 handled = true;
2114 } else {
2115 break;
2116 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08002119 } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002120 handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_DOWN);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 }
2122 break;
2123
2124 case KeyEvent.KEYCODE_DPAD_LEFT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002125 if (event.hasNoModifiers()) {
2126 handled = handleHorizontalFocusWithinListItem(View.FOCUS_LEFT);
2127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 break;
Jeff Brown4e6319b2010-12-13 10:36:51 -08002129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 case KeyEvent.KEYCODE_DPAD_RIGHT:
Jeff Brown4e6319b2010-12-13 10:36:51 -08002131 if (event.hasNoModifiers()) {
2132 handled = handleHorizontalFocusWithinListItem(View.FOCUS_RIGHT);
2133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 break;
2135
2136 case KeyEvent.KEYCODE_DPAD_CENTER:
2137 case KeyEvent.KEYCODE_ENTER:
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002138 if (event.hasNoModifiers()) {
2139 handled = resurrectSelectionIfNeeded();
2140 if (!handled
2141 && event.getRepeatCount() == 0 && getChildCount() > 0) {
2142 keyPressed();
2143 handled = true;
2144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 break;
2147
2148 case KeyEvent.KEYCODE_SPACE:
2149 if (mPopup == null || !mPopup.isShowing()) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08002150 if (event.hasNoModifiers()) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002151 handled = resurrectSelectionIfNeeded() || pageScroll(FOCUS_DOWN);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002152 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002153 handled = resurrectSelectionIfNeeded() || pageScroll(FOCUS_UP);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 }
2155 handled = true;
2156 }
2157 break;
Jeff Brown4e6319b2010-12-13 10:36:51 -08002158
2159 case KeyEvent.KEYCODE_PAGE_UP:
2160 if (event.hasNoModifiers()) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002161 handled = resurrectSelectionIfNeeded() || pageScroll(FOCUS_UP);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002162 } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002163 handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_UP);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002164 }
2165 break;
2166
2167 case KeyEvent.KEYCODE_PAGE_DOWN:
2168 if (event.hasNoModifiers()) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002169 handled = resurrectSelectionIfNeeded() || pageScroll(FOCUS_DOWN);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002170 } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002171 handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_DOWN);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002172 }
2173 break;
2174
2175 case KeyEvent.KEYCODE_MOVE_HOME:
2176 if (event.hasNoModifiers()) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002177 handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_UP);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002178 }
2179 break;
2180
2181 case KeyEvent.KEYCODE_MOVE_END:
2182 if (event.hasNoModifiers()) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002183 handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_DOWN);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002184 }
2185 break;
2186
2187 case KeyEvent.KEYCODE_TAB:
2188 // XXX Sometimes it is useful to be able to TAB through the items in
2189 // a ListView sequentially. Unfortunately this can create an
2190 // asymmetry in TAB navigation order unless the list selection
2191 // always reverts to the top or bottom when receiving TAB focus from
2192 // another widget. Leaving this behavior disabled for now but
2193 // perhaps it should be configurable (and more comprehensive).
2194 if (false) {
2195 if (event.hasNoModifiers()) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002196 handled = resurrectSelectionIfNeeded() || arrowScroll(FOCUS_DOWN);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002197 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002198 handled = resurrectSelectionIfNeeded() || arrowScroll(FOCUS_UP);
Jeff Brown4e6319b2010-12-13 10:36:51 -08002199 }
2200 }
2201 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 }
2203 }
2204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 if (handled) {
2206 return true;
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002209 if (sendToTextFilter(keyCode, count, event)) {
2210 return true;
2211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002213 switch (action) {
2214 case KeyEvent.ACTION_DOWN:
2215 return super.onKeyDown(keyCode, event);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216
Jeff Brown8d6d3b82011-01-26 19:31:18 -08002217 case KeyEvent.ACTION_UP:
2218 return super.onKeyUp(keyCode, event);
2219
2220 case KeyEvent.ACTION_MULTIPLE:
2221 return super.onKeyMultiple(keyCode, count, event);
2222
2223 default: // shouldn't happen
2224 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225 }
2226 }
2227
2228 /**
2229 * Scrolls up or down by the number of items currently present on screen.
2230 *
2231 * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
2232 * @return whether selection was moved
2233 */
2234 boolean pageScroll(int direction) {
2235 int nextPage = -1;
2236 boolean down = false;
2237
2238 if (direction == FOCUS_UP) {
2239 nextPage = Math.max(0, mSelectedPosition - getChildCount() - 1);
2240 } else if (direction == FOCUS_DOWN) {
2241 nextPage = Math.min(mItemCount - 1, mSelectedPosition + getChildCount() - 1);
2242 down = true;
2243 }
2244
2245 if (nextPage >= 0) {
2246 int position = lookForSelectablePosition(nextPage, down);
2247 if (position >= 0) {
2248 mLayoutMode = LAYOUT_SPECIFIC;
2249 mSpecificTop = mPaddingTop + getVerticalFadingEdgeLength();
2250
2251 if (down && position > mItemCount - getChildCount()) {
2252 mLayoutMode = LAYOUT_FORCE_BOTTOM;
2253 }
2254
2255 if (!down && position < getChildCount()) {
2256 mLayoutMode = LAYOUT_FORCE_TOP;
2257 }
2258
2259 setSelectionInt(position);
2260 invokeOnItemScrollListener();
Mike Cleronf116bf82009-09-27 19:14:12 -07002261 if (!awakenScrollBars()) {
2262 invalidate();
2263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264
2265 return true;
2266 }
2267 }
2268
2269 return false;
2270 }
2271
2272 /**
2273 * Go to the last or first item if possible (not worrying about panning across or navigating
2274 * within the internal focus of the currently selected item.)
2275 *
2276 * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
2277 *
2278 * @return whether selection was moved
2279 */
2280 boolean fullScroll(int direction) {
2281 boolean moved = false;
2282 if (direction == FOCUS_UP) {
2283 if (mSelectedPosition != 0) {
2284 int position = lookForSelectablePosition(0, true);
2285 if (position >= 0) {
2286 mLayoutMode = LAYOUT_FORCE_TOP;
2287 setSelectionInt(position);
2288 invokeOnItemScrollListener();
2289 }
2290 moved = true;
2291 }
2292 } else if (direction == FOCUS_DOWN) {
2293 if (mSelectedPosition < mItemCount - 1) {
2294 int position = lookForSelectablePosition(mItemCount - 1, true);
2295 if (position >= 0) {
2296 mLayoutMode = LAYOUT_FORCE_BOTTOM;
2297 setSelectionInt(position);
2298 invokeOnItemScrollListener();
2299 }
2300 moved = true;
2301 }
2302 }
2303
Mike Cleronf116bf82009-09-27 19:14:12 -07002304 if (moved && !awakenScrollBars()) {
2305 awakenScrollBars();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 invalidate();
2307 }
2308
2309 return moved;
2310 }
2311
2312 /**
2313 * To avoid horizontal focus searches changing the selected item, we
2314 * manually focus search within the selected item (as applicable), and
2315 * prevent focus from jumping to something within another item.
2316 * @param direction one of {View.FOCUS_LEFT, View.FOCUS_RIGHT}
2317 * @return Whether this consumes the key event.
2318 */
2319 private boolean handleHorizontalFocusWithinListItem(int direction) {
2320 if (direction != View.FOCUS_LEFT && direction != View.FOCUS_RIGHT) {
Romain Guy304eefa2009-03-24 20:01:49 -07002321 throw new IllegalArgumentException("direction must be one of"
2322 + " {View.FOCUS_LEFT, View.FOCUS_RIGHT}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 }
2324
2325 final int numChildren = getChildCount();
2326 if (mItemsCanFocus && numChildren > 0 && mSelectedPosition != INVALID_POSITION) {
2327 final View selectedView = getSelectedView();
Romain Guy304eefa2009-03-24 20:01:49 -07002328 if (selectedView != null && selectedView.hasFocus() &&
2329 selectedView instanceof ViewGroup) {
2330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 final View currentFocus = selectedView.findFocus();
2332 final View nextFocus = FocusFinder.getInstance().findNextFocus(
Romain Guy304eefa2009-03-24 20:01:49 -07002333 (ViewGroup) selectedView, currentFocus, direction);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002334 if (nextFocus != null) {
2335 // do the math to get interesting rect in next focus' coordinates
2336 currentFocus.getFocusedRect(mTempRect);
2337 offsetDescendantRectToMyCoords(currentFocus, mTempRect);
2338 offsetRectIntoDescendantCoords(nextFocus, mTempRect);
2339 if (nextFocus.requestFocus(direction, mTempRect)) {
2340 return true;
2341 }
2342 }
2343 // we are blocking the key from being handled (by returning true)
2344 // if the global result is going to be some other view within this
2345 // list. this is to acheive the overall goal of having
2346 // horizontal d-pad navigation remain in the current item.
Romain Guy304eefa2009-03-24 20:01:49 -07002347 final View globalNextFocus = FocusFinder.getInstance().findNextFocus(
2348 (ViewGroup) getRootView(), currentFocus, direction);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 if (globalNextFocus != null) {
2350 return isViewAncestorOf(globalNextFocus, this);
2351 }
2352 }
2353 }
2354 return false;
2355 }
2356
2357 /**
2358 * Scrolls to the next or previous item if possible.
2359 *
2360 * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN}
2361 *
2362 * @return whether selection was moved
2363 */
2364 boolean arrowScroll(int direction) {
2365 try {
2366 mInLayout = true;
2367 final boolean handled = arrowScrollImpl(direction);
2368 if (handled) {
2369 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2370 }
2371 return handled;
2372 } finally {
2373 mInLayout = false;
2374 }
2375 }
2376
2377 /**
2378 * Handle an arrow scroll going up or down. Take into account whether items are selectable,
2379 * whether there are focusable items etc.
2380 *
2381 * @param direction Either {@link android.view.View#FOCUS_UP} or {@link android.view.View#FOCUS_DOWN}.
2382 * @return Whether any scrolling, selection or focus change occured.
2383 */
2384 private boolean arrowScrollImpl(int direction) {
2385 if (getChildCount() <= 0) {
2386 return false;
2387 }
2388
2389 View selectedView = getSelectedView();
Dianne Hackborn079e2352010-10-18 17:02:43 -07002390 int selectedPos = mSelectedPosition;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391
2392 int nextSelectedPosition = lookForSelectablePositionOnScreen(direction);
2393 int amountToScroll = amountToScroll(direction, nextSelectedPosition);
2394
2395 // if we are moving focus, we may OVERRIDE the default behavior
2396 final ArrowScrollFocusResult focusResult = mItemsCanFocus ? arrowScrollFocused(direction) : null;
2397 if (focusResult != null) {
2398 nextSelectedPosition = focusResult.getSelectedPosition();
2399 amountToScroll = focusResult.getAmountToScroll();
2400 }
2401
2402 boolean needToRedraw = focusResult != null;
2403 if (nextSelectedPosition != INVALID_POSITION) {
2404 handleNewSelectionChange(selectedView, direction, nextSelectedPosition, focusResult != null);
2405 setSelectedPositionInt(nextSelectedPosition);
2406 setNextSelectedPositionInt(nextSelectedPosition);
2407 selectedView = getSelectedView();
Dianne Hackborn079e2352010-10-18 17:02:43 -07002408 selectedPos = nextSelectedPosition;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 if (mItemsCanFocus && focusResult == null) {
2410 // there was no new view found to take focus, make sure we
2411 // don't leave focus with the old selection
2412 final View focused = getFocusedChild();
2413 if (focused != null) {
2414 focused.clearFocus();
2415 }
2416 }
2417 needToRedraw = true;
2418 checkSelectionChanged();
2419 }
2420
2421 if (amountToScroll > 0) {
2422 scrollListItemsBy((direction == View.FOCUS_UP) ? amountToScroll : -amountToScroll);
2423 needToRedraw = true;
2424 }
2425
2426 // if we didn't find a new focusable, make sure any existing focused
2427 // item that was panned off screen gives up focus.
2428 if (mItemsCanFocus && (focusResult == null)
2429 && selectedView != null && selectedView.hasFocus()) {
2430 final View focused = selectedView.findFocus();
Mark Brophy1ea68892011-08-01 16:24:44 +01002431 if (!isViewAncestorOf(focused, this) || distanceToView(focused) > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 focused.clearFocus();
2433 }
2434 }
2435
2436 // if the current selection is panned off, we need to remove the selection
2437 if (nextSelectedPosition == INVALID_POSITION && selectedView != null
2438 && !isViewAncestorOf(selectedView, this)) {
2439 selectedView = null;
2440 hideSelector();
2441
2442 // but we don't want to set the ressurect position (that would make subsequent
2443 // unhandled key events bring back the item we just scrolled off!)
2444 mResurrectToPosition = INVALID_POSITION;
2445 }
2446
2447 if (needToRedraw) {
2448 if (selectedView != null) {
Dianne Hackborn079e2352010-10-18 17:02:43 -07002449 positionSelector(selectedPos, selectedView);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 mSelectedTop = selectedView.getTop();
2451 }
Mike Cleronf116bf82009-09-27 19:14:12 -07002452 if (!awakenScrollBars()) {
2453 invalidate();
2454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 invokeOnItemScrollListener();
2456 return true;
2457 }
2458
2459 return false;
2460 }
2461
2462 /**
2463 * When selection changes, it is possible that the previously selected or the
2464 * next selected item will change its size. If so, we need to offset some folks,
2465 * and re-layout the items as appropriate.
2466 *
2467 * @param selectedView The currently selected view (before changing selection).
2468 * should be <code>null</code> if there was no previous selection.
2469 * @param direction Either {@link android.view.View#FOCUS_UP} or
2470 * {@link android.view.View#FOCUS_DOWN}.
2471 * @param newSelectedPosition The position of the next selection.
2472 * @param newFocusAssigned whether new focus was assigned. This matters because
2473 * when something has focus, we don't want to show selection (ugh).
2474 */
2475 private void handleNewSelectionChange(View selectedView, int direction, int newSelectedPosition,
2476 boolean newFocusAssigned) {
2477 if (newSelectedPosition == INVALID_POSITION) {
2478 throw new IllegalArgumentException("newSelectedPosition needs to be valid");
2479 }
2480
2481 // whether or not we are moving down or up, we want to preserve the
2482 // top of whatever view is on top:
2483 // - moving down: the view that had selection
2484 // - moving up: the view that is getting selection
2485 View topView;
2486 View bottomView;
2487 int topViewIndex, bottomViewIndex;
2488 boolean topSelected = false;
2489 final int selectedIndex = mSelectedPosition - mFirstPosition;
2490 final int nextSelectedIndex = newSelectedPosition - mFirstPosition;
2491 if (direction == View.FOCUS_UP) {
2492 topViewIndex = nextSelectedIndex;
2493 bottomViewIndex = selectedIndex;
2494 topView = getChildAt(topViewIndex);
2495 bottomView = selectedView;
2496 topSelected = true;
2497 } else {
2498 topViewIndex = selectedIndex;
2499 bottomViewIndex = nextSelectedIndex;
2500 topView = selectedView;
2501 bottomView = getChildAt(bottomViewIndex);
2502 }
2503
2504 final int numChildren = getChildCount();
2505
2506 // start with top view: is it changing size?
2507 if (topView != null) {
2508 topView.setSelected(!newFocusAssigned && topSelected);
2509 measureAndAdjustDown(topView, topViewIndex, numChildren);
2510 }
2511
2512 // is the bottom view changing size?
2513 if (bottomView != null) {
2514 bottomView.setSelected(!newFocusAssigned && !topSelected);
2515 measureAndAdjustDown(bottomView, bottomViewIndex, numChildren);
2516 }
2517 }
2518
2519 /**
2520 * Re-measure a child, and if its height changes, lay it out preserving its
2521 * top, and adjust the children below it appropriately.
2522 * @param child The child
2523 * @param childIndex The view group index of the child.
2524 * @param numChildren The number of children in the view group.
2525 */
2526 private void measureAndAdjustDown(View child, int childIndex, int numChildren) {
2527 int oldHeight = child.getHeight();
2528 measureItem(child);
2529 if (child.getMeasuredHeight() != oldHeight) {
2530 // lay out the view, preserving its top
2531 relayoutMeasuredItem(child);
2532
2533 // adjust views below appropriately
2534 final int heightDelta = child.getMeasuredHeight() - oldHeight;
2535 for (int i = childIndex + 1; i < numChildren; i++) {
2536 getChildAt(i).offsetTopAndBottom(heightDelta);
2537 }
2538 }
2539 }
2540
2541 /**
2542 * Measure a particular list child.
2543 * TODO: unify with setUpChild.
2544 * @param child The child.
2545 */
2546 private void measureItem(View child) {
2547 ViewGroup.LayoutParams p = child.getLayoutParams();
2548 if (p == null) {
2549 p = new ViewGroup.LayoutParams(
Romain Guy980a9382010-01-08 15:06:28 -08002550 ViewGroup.LayoutParams.MATCH_PARENT,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 ViewGroup.LayoutParams.WRAP_CONTENT);
2552 }
2553
2554 int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
2555 mListPadding.left + mListPadding.right, p.width);
2556 int lpHeight = p.height;
2557 int childHeightSpec;
2558 if (lpHeight > 0) {
2559 childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
2560 } else {
2561 childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
2562 }
2563 child.measure(childWidthSpec, childHeightSpec);
2564 }
2565
2566 /**
2567 * Layout a child that has been measured, preserving its top position.
2568 * TODO: unify with setUpChild.
2569 * @param child The child.
2570 */
2571 private void relayoutMeasuredItem(View child) {
2572 final int w = child.getMeasuredWidth();
2573 final int h = child.getMeasuredHeight();
2574 final int childLeft = mListPadding.left;
2575 final int childRight = childLeft + w;
2576 final int childTop = child.getTop();
2577 final int childBottom = childTop + h;
2578 child.layout(childLeft, childTop, childRight, childBottom);
2579 }
2580
2581 /**
2582 * @return The amount to preview next items when arrow srolling.
2583 */
2584 private int getArrowScrollPreviewLength() {
2585 return Math.max(MIN_SCROLL_PREVIEW_PIXELS, getVerticalFadingEdgeLength());
2586 }
2587
2588 /**
2589 * Determine how much we need to scroll in order to get the next selected view
2590 * visible, with a fading edge showing below as applicable. The amount is
2591 * capped at {@link #getMaxScrollAmount()} .
2592 *
2593 * @param direction either {@link android.view.View#FOCUS_UP} or
2594 * {@link android.view.View#FOCUS_DOWN}.
2595 * @param nextSelectedPosition The position of the next selection, or
2596 * {@link #INVALID_POSITION} if there is no next selectable position
2597 * @return The amount to scroll. Note: this is always positive! Direction
2598 * needs to be taken into account when actually scrolling.
2599 */
2600 private int amountToScroll(int direction, int nextSelectedPosition) {
2601 final int listBottom = getHeight() - mListPadding.bottom;
2602 final int listTop = mListPadding.top;
2603
2604 final int numChildren = getChildCount();
2605
2606 if (direction == View.FOCUS_DOWN) {
2607 int indexToMakeVisible = numChildren - 1;
2608 if (nextSelectedPosition != INVALID_POSITION) {
2609 indexToMakeVisible = nextSelectedPosition - mFirstPosition;
2610 }
2611
2612 final int positionToMakeVisible = mFirstPosition + indexToMakeVisible;
2613 final View viewToMakeVisible = getChildAt(indexToMakeVisible);
2614
2615 int goalBottom = listBottom;
2616 if (positionToMakeVisible < mItemCount - 1) {
2617 goalBottom -= getArrowScrollPreviewLength();
2618 }
2619
2620 if (viewToMakeVisible.getBottom() <= goalBottom) {
2621 // item is fully visible.
2622 return 0;
2623 }
2624
2625 if (nextSelectedPosition != INVALID_POSITION
2626 && (goalBottom - viewToMakeVisible.getTop()) >= getMaxScrollAmount()) {
2627 // item already has enough of it visible, changing selection is good enough
2628 return 0;
2629 }
2630
2631 int amountToScroll = (viewToMakeVisible.getBottom() - goalBottom);
2632
2633 if ((mFirstPosition + numChildren) == mItemCount) {
2634 // last is last in list -> make sure we don't scroll past it
2635 final int max = getChildAt(numChildren - 1).getBottom() - listBottom;
2636 amountToScroll = Math.min(amountToScroll, max);
2637 }
2638
2639 return Math.min(amountToScroll, getMaxScrollAmount());
2640 } else {
2641 int indexToMakeVisible = 0;
2642 if (nextSelectedPosition != INVALID_POSITION) {
2643 indexToMakeVisible = nextSelectedPosition - mFirstPosition;
2644 }
2645 final int positionToMakeVisible = mFirstPosition + indexToMakeVisible;
2646 final View viewToMakeVisible = getChildAt(indexToMakeVisible);
2647 int goalTop = listTop;
2648 if (positionToMakeVisible > 0) {
2649 goalTop += getArrowScrollPreviewLength();
2650 }
2651 if (viewToMakeVisible.getTop() >= goalTop) {
2652 // item is fully visible.
2653 return 0;
2654 }
2655
2656 if (nextSelectedPosition != INVALID_POSITION &&
2657 (viewToMakeVisible.getBottom() - goalTop) >= getMaxScrollAmount()) {
2658 // item already has enough of it visible, changing selection is good enough
2659 return 0;
2660 }
2661
2662 int amountToScroll = (goalTop - viewToMakeVisible.getTop());
2663 if (mFirstPosition == 0) {
2664 // first is first in list -> make sure we don't scroll past it
2665 final int max = listTop - getChildAt(0).getTop();
2666 amountToScroll = Math.min(amountToScroll, max);
2667 }
2668 return Math.min(amountToScroll, getMaxScrollAmount());
2669 }
2670 }
2671
2672 /**
2673 * Holds results of focus aware arrow scrolling.
2674 */
2675 static private class ArrowScrollFocusResult {
2676 private int mSelectedPosition;
2677 private int mAmountToScroll;
2678
2679 /**
2680 * How {@link android.widget.ListView#arrowScrollFocused} returns its values.
2681 */
2682 void populate(int selectedPosition, int amountToScroll) {
2683 mSelectedPosition = selectedPosition;
2684 mAmountToScroll = amountToScroll;
2685 }
2686
2687 public int getSelectedPosition() {
2688 return mSelectedPosition;
2689 }
2690
2691 public int getAmountToScroll() {
2692 return mAmountToScroll;
2693 }
2694 }
2695
2696 /**
2697 * @param direction either {@link android.view.View#FOCUS_UP} or
2698 * {@link android.view.View#FOCUS_DOWN}.
2699 * @return The position of the next selectable position of the views that
2700 * are currently visible, taking into account the fact that there might
2701 * be no selection. Returns {@link #INVALID_POSITION} if there is no
2702 * selectable view on screen in the given direction.
2703 */
2704 private int lookForSelectablePositionOnScreen(int direction) {
2705 final int firstPosition = mFirstPosition;
2706 if (direction == View.FOCUS_DOWN) {
2707 int startPos = (mSelectedPosition != INVALID_POSITION) ?
2708 mSelectedPosition + 1 :
2709 firstPosition;
2710 if (startPos >= mAdapter.getCount()) {
2711 return INVALID_POSITION;
2712 }
2713 if (startPos < firstPosition) {
2714 startPos = firstPosition;
2715 }
2716
2717 final int lastVisiblePos = getLastVisiblePosition();
2718 final ListAdapter adapter = getAdapter();
2719 for (int pos = startPos; pos <= lastVisiblePos; pos++) {
2720 if (adapter.isEnabled(pos)
2721 && getChildAt(pos - firstPosition).getVisibility() == View.VISIBLE) {
2722 return pos;
2723 }
2724 }
2725 } else {
2726 int last = firstPosition + getChildCount() - 1;
2727 int startPos = (mSelectedPosition != INVALID_POSITION) ?
2728 mSelectedPosition - 1 :
2729 firstPosition + getChildCount() - 1;
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002730 if (startPos < 0 || startPos >= mAdapter.getCount()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 return INVALID_POSITION;
2732 }
2733 if (startPos > last) {
2734 startPos = last;
2735 }
2736
2737 final ListAdapter adapter = getAdapter();
2738 for (int pos = startPos; pos >= firstPosition; pos--) {
2739 if (adapter.isEnabled(pos)
2740 && getChildAt(pos - firstPosition).getVisibility() == View.VISIBLE) {
2741 return pos;
2742 }
2743 }
2744 }
2745 return INVALID_POSITION;
2746 }
2747
2748 /**
2749 * Do an arrow scroll based on focus searching. If a new view is
2750 * given focus, return the selection delta and amount to scroll via
2751 * an {@link ArrowScrollFocusResult}, otherwise, return null.
2752 *
2753 * @param direction either {@link android.view.View#FOCUS_UP} or
2754 * {@link android.view.View#FOCUS_DOWN}.
2755 * @return The result if focus has changed, or <code>null</code>.
2756 */
2757 private ArrowScrollFocusResult arrowScrollFocused(final int direction) {
2758 final View selectedView = getSelectedView();
2759 View newFocus;
2760 if (selectedView != null && selectedView.hasFocus()) {
2761 View oldFocus = selectedView.findFocus();
2762 newFocus = FocusFinder.getInstance().findNextFocus(this, oldFocus, direction);
2763 } else {
2764 if (direction == View.FOCUS_DOWN) {
2765 final boolean topFadingEdgeShowing = (mFirstPosition > 0);
2766 final int listTop = mListPadding.top +
2767 (topFadingEdgeShowing ? getArrowScrollPreviewLength() : 0);
2768 final int ySearchPoint =
2769 (selectedView != null && selectedView.getTop() > listTop) ?
2770 selectedView.getTop() :
2771 listTop;
2772 mTempRect.set(0, ySearchPoint, 0, ySearchPoint);
2773 } else {
2774 final boolean bottomFadingEdgeShowing =
2775 (mFirstPosition + getChildCount() - 1) < mItemCount;
2776 final int listBottom = getHeight() - mListPadding.bottom -
2777 (bottomFadingEdgeShowing ? getArrowScrollPreviewLength() : 0);
2778 final int ySearchPoint =
2779 (selectedView != null && selectedView.getBottom() < listBottom) ?
2780 selectedView.getBottom() :
2781 listBottom;
2782 mTempRect.set(0, ySearchPoint, 0, ySearchPoint);
2783 }
2784 newFocus = FocusFinder.getInstance().findNextFocusFromRect(this, mTempRect, direction);
2785 }
2786
2787 if (newFocus != null) {
2788 final int positionOfNewFocus = positionOfNewFocus(newFocus);
2789
2790 // if the focus change is in a different new position, make sure
2791 // we aren't jumping over another selectable position
2792 if (mSelectedPosition != INVALID_POSITION && positionOfNewFocus != mSelectedPosition) {
2793 final int selectablePosition = lookForSelectablePositionOnScreen(direction);
2794 if (selectablePosition != INVALID_POSITION &&
2795 ((direction == View.FOCUS_DOWN && selectablePosition < positionOfNewFocus) ||
2796 (direction == View.FOCUS_UP && selectablePosition > positionOfNewFocus))) {
2797 return null;
2798 }
2799 }
2800
2801 int focusScroll = amountToScrollToNewFocus(direction, newFocus, positionOfNewFocus);
2802
2803 final int maxScrollAmount = getMaxScrollAmount();
2804 if (focusScroll < maxScrollAmount) {
2805 // not moving too far, safe to give next view focus
2806 newFocus.requestFocus(direction);
2807 mArrowScrollFocusResult.populate(positionOfNewFocus, focusScroll);
2808 return mArrowScrollFocusResult;
2809 } else if (distanceToView(newFocus) < maxScrollAmount){
2810 // Case to consider:
2811 // too far to get entire next focusable on screen, but by going
2812 // max scroll amount, we are getting it at least partially in view,
2813 // so give it focus and scroll the max ammount.
2814 newFocus.requestFocus(direction);
2815 mArrowScrollFocusResult.populate(positionOfNewFocus, maxScrollAmount);
2816 return mArrowScrollFocusResult;
2817 }
2818 }
2819 return null;
2820 }
2821
2822 /**
2823 * @param newFocus The view that would have focus.
2824 * @return the position that contains newFocus
2825 */
2826 private int positionOfNewFocus(View newFocus) {
2827 final int numChildren = getChildCount();
2828 for (int i = 0; i < numChildren; i++) {
2829 final View child = getChildAt(i);
2830 if (isViewAncestorOf(newFocus, child)) {
2831 return mFirstPosition + i;
2832 }
2833 }
2834 throw new IllegalArgumentException("newFocus is not a child of any of the"
2835 + " children of the list!");
2836 }
2837
2838 /**
2839 * Return true if child is an ancestor of parent, (or equal to the parent).
2840 */
2841 private boolean isViewAncestorOf(View child, View parent) {
2842 if (child == parent) {
2843 return true;
2844 }
2845
2846 final ViewParent theParent = child.getParent();
2847 return (theParent instanceof ViewGroup) && isViewAncestorOf((View) theParent, parent);
2848 }
2849
2850 /**
2851 * Determine how much we need to scroll in order to get newFocus in view.
2852 * @param direction either {@link android.view.View#FOCUS_UP} or
2853 * {@link android.view.View#FOCUS_DOWN}.
2854 * @param newFocus The view that would take focus.
2855 * @param positionOfNewFocus The position of the list item containing newFocus
2856 * @return The amount to scroll. Note: this is always positive! Direction
2857 * needs to be taken into account when actually scrolling.
2858 */
2859 private int amountToScrollToNewFocus(int direction, View newFocus, int positionOfNewFocus) {
2860 int amountToScroll = 0;
2861 newFocus.getDrawingRect(mTempRect);
2862 offsetDescendantRectToMyCoords(newFocus, mTempRect);
2863 if (direction == View.FOCUS_UP) {
2864 if (mTempRect.top < mListPadding.top) {
2865 amountToScroll = mListPadding.top - mTempRect.top;
2866 if (positionOfNewFocus > 0) {
2867 amountToScroll += getArrowScrollPreviewLength();
2868 }
2869 }
2870 } else {
2871 final int listBottom = getHeight() - mListPadding.bottom;
2872 if (mTempRect.bottom > listBottom) {
2873 amountToScroll = mTempRect.bottom - listBottom;
2874 if (positionOfNewFocus < mItemCount - 1) {
2875 amountToScroll += getArrowScrollPreviewLength();
2876 }
2877 }
2878 }
2879 return amountToScroll;
2880 }
2881
2882 /**
2883 * Determine the distance to the nearest edge of a view in a particular
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -08002884 * direction.
2885 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 * @param descendant A descendant of this list.
2887 * @return The distance, or 0 if the nearest edge is already on screen.
2888 */
2889 private int distanceToView(View descendant) {
2890 int distance = 0;
2891 descendant.getDrawingRect(mTempRect);
2892 offsetDescendantRectToMyCoords(descendant, mTempRect);
2893 final int listBottom = mBottom - mTop - mListPadding.bottom;
2894 if (mTempRect.bottom < mListPadding.top) {
2895 distance = mListPadding.top - mTempRect.bottom;
2896 } else if (mTempRect.top > listBottom) {
2897 distance = mTempRect.top - listBottom;
2898 }
2899 return distance;
2900 }
2901
2902
2903 /**
2904 * Scroll the children by amount, adding a view at the end and removing
2905 * views that fall off as necessary.
2906 *
2907 * @param amount The amount (positive or negative) to scroll.
2908 */
2909 private void scrollListItemsBy(int amount) {
2910 offsetChildrenTopAndBottom(amount);
2911
2912 final int listBottom = getHeight() - mListPadding.bottom;
2913 final int listTop = mListPadding.top;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002914 final AbsListView.RecycleBin recycleBin = mRecycler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915
2916 if (amount < 0) {
2917 // shifted items up
2918
2919 // may need to pan views into the bottom space
2920 int numChildren = getChildCount();
2921 View last = getChildAt(numChildren - 1);
2922 while (last.getBottom() < listBottom) {
2923 final int lastVisiblePosition = mFirstPosition + numChildren - 1;
2924 if (lastVisiblePosition < mItemCount - 1) {
2925 last = addViewBelow(last, lastVisiblePosition);
2926 numChildren++;
2927 } else {
2928 break;
2929 }
2930 }
2931
2932 // may have brought in the last child of the list that is skinnier
2933 // than the fading edge, thereby leaving space at the end. need
2934 // to shift back
2935 if (last.getBottom() < listBottom) {
2936 offsetChildrenTopAndBottom(listBottom - last.getBottom());
2937 }
2938
2939 // top views may be panned off screen
2940 View first = getChildAt(0);
2941 while (first.getBottom() < listTop) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002942 AbsListView.LayoutParams layoutParams = (LayoutParams) first.getLayoutParams();
2943 if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) {
Romain Guy2d51bff2010-01-19 17:34:10 -08002944 detachViewFromParent(first);
Dianne Hackborn079e2352010-10-18 17:02:43 -07002945 recycleBin.addScrapView(first, mFirstPosition);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002946 } else {
Romain Guy2d51bff2010-01-19 17:34:10 -08002947 removeViewInLayout(first);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949 first = getChildAt(0);
2950 mFirstPosition++;
2951 }
2952 } else {
2953 // shifted items down
2954 View first = getChildAt(0);
2955
2956 // may need to pan views into top
2957 while ((first.getTop() > listTop) && (mFirstPosition > 0)) {
2958 first = addViewAbove(first, mFirstPosition);
2959 mFirstPosition--;
2960 }
2961
2962 // may have brought the very first child of the list in too far and
2963 // need to shift it back
2964 if (first.getTop() > listTop) {
2965 offsetChildrenTopAndBottom(listTop - first.getTop());
2966 }
2967
2968 int lastIndex = getChildCount() - 1;
2969 View last = getChildAt(lastIndex);
2970
2971 // bottom view may be panned off screen
2972 while (last.getTop() > listBottom) {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002973 AbsListView.LayoutParams layoutParams = (LayoutParams) last.getLayoutParams();
2974 if (recycleBin.shouldRecycleViewType(layoutParams.viewType)) {
Romain Guy2d51bff2010-01-19 17:34:10 -08002975 detachViewFromParent(last);
Dianne Hackborn079e2352010-10-18 17:02:43 -07002976 recycleBin.addScrapView(last, mFirstPosition+lastIndex);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002977 } else {
Romain Guy2d51bff2010-01-19 17:34:10 -08002978 removeViewInLayout(last);
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 last = getChildAt(--lastIndex);
2981 }
2982 }
2983 }
2984
2985 private View addViewAbove(View theView, int position) {
2986 int abovePosition = position - 1;
Romain Guy21875052010-01-06 18:48:08 -08002987 View view = obtainView(abovePosition, mIsScrap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 int edgeOfNewChild = theView.getTop() - mDividerHeight;
Romain Guy21875052010-01-06 18:48:08 -08002989 setupChild(view, abovePosition, edgeOfNewChild, false, mListPadding.left,
2990 false, mIsScrap[0]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 return view;
2992 }
2993
2994 private View addViewBelow(View theView, int position) {
2995 int belowPosition = position + 1;
Romain Guy21875052010-01-06 18:48:08 -08002996 View view = obtainView(belowPosition, mIsScrap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 int edgeOfNewChild = theView.getBottom() + mDividerHeight;
Romain Guy21875052010-01-06 18:48:08 -08002998 setupChild(view, belowPosition, edgeOfNewChild, true, mListPadding.left,
2999 false, mIsScrap[0]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000 return view;
3001 }
3002
3003 /**
3004 * Indicates that the views created by the ListAdapter can contain focusable
3005 * items.
3006 *
3007 * @param itemsCanFocus true if items can get focus, false otherwise
3008 */
3009 public void setItemsCanFocus(boolean itemsCanFocus) {
3010 mItemsCanFocus = itemsCanFocus;
3011 if (!itemsCanFocus) {
3012 setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
3013 }
3014 }
3015
3016 /**
3017 * @return Whether the views created by the ListAdapter can contain focusable
3018 * items.
3019 */
3020 public boolean getItemsCanFocus() {
3021 return mItemsCanFocus;
3022 }
3023
3024 @Override
Romain Guy24443ea2009-05-11 11:56:30 -07003025 public boolean isOpaque() {
Chet Haase78400552011-03-03 08:18:17 -08003026 boolean retValue = (mCachingActive && mIsCacheColorOpaque && mDividerIsOpaque &&
Romain Guy8f1344f2009-05-15 16:03:59 -07003027 hasOpaqueScrollbars()) || super.isOpaque();
Chet Haase78400552011-03-03 08:18:17 -08003028 if (retValue) {
3029 // only return true if the list items cover the entire area of the view
Adam Powell3ba8f5d2011-03-07 15:36:33 -08003030 final int listTop = mListPadding != null ? mListPadding.top : mPaddingTop;
Chet Haase78400552011-03-03 08:18:17 -08003031 View first = getChildAt(0);
3032 if (first == null || first.getTop() > listTop) {
3033 return false;
3034 }
Adam Powell3ba8f5d2011-03-07 15:36:33 -08003035 final int listBottom = getHeight() -
3036 (mListPadding != null ? mListPadding.bottom : mPaddingBottom);
Chet Haase78400552011-03-03 08:18:17 -08003037 View last = getChildAt(getChildCount() - 1);
3038 if (last == null || last.getBottom() < listBottom) {
3039 return false;
3040 }
3041 }
3042 return retValue;
Romain Guy24443ea2009-05-11 11:56:30 -07003043 }
3044
3045 @Override
3046 public void setCacheColorHint(int color) {
Romain Guy8f1344f2009-05-15 16:03:59 -07003047 final boolean opaque = (color >>> 24) == 0xFF;
3048 mIsCacheColorOpaque = opaque;
3049 if (opaque) {
Romain Guya02903f2009-05-23 13:26:46 -07003050 if (mDividerPaint == null) {
3051 mDividerPaint = new Paint();
3052 }
Romain Guy8f1344f2009-05-15 16:03:59 -07003053 mDividerPaint.setColor(color);
3054 }
Romain Guy24443ea2009-05-11 11:56:30 -07003055 super.setCacheColorHint(color);
3056 }
Adam Powell637d3372010-08-25 14:37:03 -07003057
3058 void drawOverscrollHeader(Canvas canvas, Drawable drawable, Rect bounds) {
3059 final int height = drawable.getMinimumHeight();
3060
3061 canvas.save();
3062 canvas.clipRect(bounds);
3063
3064 final int span = bounds.bottom - bounds.top;
3065 if (span < height) {
3066 bounds.top = bounds.bottom - height;
3067 }
3068
3069 drawable.setBounds(bounds);
3070 drawable.draw(canvas);
3071
3072 canvas.restore();
3073 }
3074
3075 void drawOverscrollFooter(Canvas canvas, Drawable drawable, Rect bounds) {
3076 final int height = drawable.getMinimumHeight();
3077
3078 canvas.save();
3079 canvas.clipRect(bounds);
3080
3081 final int span = bounds.bottom - bounds.top;
3082 if (span < height) {
3083 bounds.bottom = bounds.top + height;
3084 }
3085
3086 drawable.setBounds(bounds);
3087 drawable.draw(canvas);
3088
3089 canvas.restore();
3090 }
3091
Romain Guy24443ea2009-05-11 11:56:30 -07003092 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093 protected void dispatchDraw(Canvas canvas) {
Romain Guy0211a0a2011-02-14 16:34:59 -08003094 if (mCachingStarted) {
3095 mCachingActive = true;
3096 }
3097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 // Draw the dividers
3099 final int dividerHeight = mDividerHeight;
Adam Powell637d3372010-08-25 14:37:03 -07003100 final Drawable overscrollHeader = mOverScrollHeader;
3101 final Drawable overscrollFooter = mOverScrollFooter;
3102 final boolean drawOverscrollHeader = overscrollHeader != null;
3103 final boolean drawOverscrollFooter = overscrollFooter != null;
Adam Powellbfb5d4b2010-03-10 18:55:25 -08003104 final boolean drawDividers = dividerHeight > 0 && mDivider != null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105
Adam Powell637d3372010-08-25 14:37:03 -07003106 if (drawDividers || drawOverscrollHeader || drawOverscrollFooter) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003107 // Only modify the top and bottom in the loop, we set the left and right here
3108 final Rect bounds = mTempRect;
3109 bounds.left = mPaddingLeft;
3110 bounds.right = mRight - mLeft - mPaddingRight;
3111
3112 final int count = getChildCount();
3113 final int headerCount = mHeaderViewInfos.size();
Adam Powellbfb5d4b2010-03-10 18:55:25 -08003114 final int itemCount = mItemCount;
3115 final int footerLimit = itemCount - mFooterViewInfos.size() - 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116 final boolean headerDividers = mHeaderDividersEnabled;
3117 final boolean footerDividers = mFooterDividersEnabled;
3118 final int first = mFirstPosition;
Romain Guy2bed2272009-03-24 18:23:21 -07003119 final boolean areAllItemsSelectable = mAreAllItemsSelectable;
3120 final ListAdapter adapter = mAdapter;
Romain Guye32edc62009-05-29 10:33:36 -07003121 // If the list is opaque *and* the background is not, we want to
3122 // fill a rect where the dividers would be for non-selectable items
3123 // If the list is opaque and the background is also opaque, we don't
3124 // need to draw anything since the background will do it for us
Romain Guy179de8a2010-07-09 13:27:00 -07003125 final boolean fillForMissingDividers = isOpaque() && !super.isOpaque();
Romain Guye32edc62009-05-29 10:33:36 -07003126
3127 if (fillForMissingDividers && mDividerPaint == null && mIsCacheColorOpaque) {
Romain Guya02903f2009-05-23 13:26:46 -07003128 mDividerPaint = new Paint();
Romain Guye32edc62009-05-29 10:33:36 -07003129 mDividerPaint.setColor(getCacheColorHint());
Romain Guya02903f2009-05-23 13:26:46 -07003130 }
Romain Guy8f1344f2009-05-15 16:03:59 -07003131 final Paint paint = mDividerPaint;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132
Adam Powell94566552011-01-05 23:25:33 -08003133 int effectivePaddingTop = 0;
3134 int effectivePaddingBottom = 0;
3135 if ((mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK) {
3136 effectivePaddingTop = mListPadding.top;
3137 effectivePaddingBottom = mListPadding.bottom;
3138 }
3139
3140 final int listBottom = mBottom - mTop - effectivePaddingBottom + mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 if (!mStackFromBottom) {
Adam Powell637d3372010-08-25 14:37:03 -07003142 int bottom = 0;
Adam Powell0b8bb422010-02-08 14:30:45 -08003143
Adam Powell637d3372010-08-25 14:37:03 -07003144 // Draw top divider or header for overscroll
3145 final int scrollY = mScrollY;
3146 if (count > 0 && scrollY < 0) {
3147 if (drawOverscrollHeader) {
3148 bounds.bottom = 0;
3149 bounds.top = scrollY;
3150 drawOverscrollHeader(canvas, overscrollHeader, bounds);
3151 } else if (drawDividers) {
3152 bounds.bottom = 0;
3153 bounds.top = -dividerHeight;
3154 drawDivider(canvas, bounds, -1);
3155 }
3156 }
3157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 for (int i = 0; i < count; i++) {
3159 if ((headerDividers || first + i >= headerCount) &&
3160 (footerDividers || first + i < footerLimit)) {
3161 View child = getChildAt(i);
3162 bottom = child.getBottom();
Romain Guy2bed2272009-03-24 18:23:21 -07003163 // Don't draw dividers next to items that are not enabled
Adam Powell637d3372010-08-25 14:37:03 -07003164
3165 if (drawDividers &&
3166 (bottom < listBottom && !(drawOverscrollFooter && i == count - 1))) {
3167 if ((areAllItemsSelectable ||
3168 (adapter.isEnabled(first + i) && (i == count - 1 ||
3169 adapter.isEnabled(first + i + 1))))) {
3170 bounds.top = bottom;
3171 bounds.bottom = bottom + dividerHeight;
3172 drawDivider(canvas, bounds, i);
3173 } else if (fillForMissingDividers) {
3174 bounds.top = bottom;
3175 bounds.bottom = bottom + dividerHeight;
3176 canvas.drawRect(bounds, paint);
3177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 }
3179 }
3180 }
Adam Powell637d3372010-08-25 14:37:03 -07003181
3182 final int overFooterBottom = mBottom + mScrollY;
3183 if (drawOverscrollFooter && first + count == itemCount &&
3184 overFooterBottom > bottom) {
3185 bounds.top = bottom;
3186 bounds.bottom = overFooterBottom;
3187 drawOverscrollFooter(canvas, overscrollFooter, bounds);
3188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003189 } else {
3190 int top;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191
Adam Powellbfb5d4b2010-03-10 18:55:25 -08003192 final int scrollY = mScrollY;
Adam Powellbfb5d4b2010-03-10 18:55:25 -08003193
Adam Powell637d3372010-08-25 14:37:03 -07003194 if (count > 0 && drawOverscrollHeader) {
3195 bounds.top = scrollY;
3196 bounds.bottom = getChildAt(0).getTop();
3197 drawOverscrollHeader(canvas, overscrollHeader, bounds);
3198 }
3199
3200 final int start = drawOverscrollHeader ? 1 : 0;
3201 for (int i = start; i < count; i++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 if ((headerDividers || first + i >= headerCount) &&
3203 (footerDividers || first + i < footerLimit)) {
3204 View child = getChildAt(i);
3205 top = child.getTop();
Romain Guy2bed2272009-03-24 18:23:21 -07003206 // Don't draw dividers next to items that are not enabled
Romain Guy0211a0a2011-02-14 16:34:59 -08003207 if (top > effectivePaddingTop) {
Romain Guy8f1344f2009-05-15 16:03:59 -07003208 if ((areAllItemsSelectable ||
3209 (adapter.isEnabled(first + i) && (i == count - 1 ||
3210 adapter.isEnabled(first + i + 1))))) {
3211 bounds.top = top - dividerHeight;
3212 bounds.bottom = top;
3213 // Give the method the child ABOVE the divider, so we
3214 // subtract one from our child
3215 // position. Give -1 when there is no child above the
3216 // divider.
3217 drawDivider(canvas, bounds, i - 1);
Romain Guye32edc62009-05-29 10:33:36 -07003218 } else if (fillForMissingDividers) {
Romain Guy8f1344f2009-05-15 16:03:59 -07003219 bounds.top = top - dividerHeight;
3220 bounds.bottom = top;
3221 canvas.drawRect(bounds, paint);
3222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 }
3224 }
3225 }
Adam Powellbfb5d4b2010-03-10 18:55:25 -08003226
Romain Guy179de8a2010-07-09 13:27:00 -07003227 if (count > 0 && scrollY > 0) {
Adam Powell637d3372010-08-25 14:37:03 -07003228 if (drawOverscrollFooter) {
3229 final int absListBottom = mBottom;
3230 bounds.top = absListBottom;
3231 bounds.bottom = absListBottom + scrollY;
3232 drawOverscrollFooter(canvas, overscrollFooter, bounds);
3233 } else if (drawDividers) {
3234 bounds.top = listBottom;
3235 bounds.bottom = listBottom + dividerHeight;
3236 drawDivider(canvas, bounds, -1);
3237 }
Adam Powellbfb5d4b2010-03-10 18:55:25 -08003238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 }
3240 }
3241
3242 // Draw the indicators (these should be drawn above the dividers) and children
3243 super.dispatchDraw(canvas);
3244 }
3245
Romain Guy0211a0a2011-02-14 16:34:59 -08003246 @Override
3247 protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
3248 boolean more = super.drawChild(canvas, child, drawingTime);
3249 if (mCachingActive && child.mCachingFailed) {
3250 mCachingActive = false;
3251 }
3252 return more;
3253 }
3254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 /**
3256 * Draws a divider for the given child in the given bounds.
3257 *
3258 * @param canvas The canvas to draw to.
3259 * @param bounds The bounds of the divider.
3260 * @param childIndex The index of child (of the View) above the divider.
3261 * This will be -1 if there is no child above the divider to be
3262 * drawn.
3263 */
3264 void drawDivider(Canvas canvas, Rect bounds, int childIndex) {
3265 // This widget draws the same divider for all children
3266 final Drawable divider = mDivider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267
Romain Guy95930e12010-10-04 13:46:02 -07003268 divider.setBounds(bounds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 divider.draw(canvas);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 }
3271
3272 /**
3273 * Returns the drawable that will be drawn between each item in the list.
3274 *
3275 * @return the current drawable drawn between list elements
3276 */
3277 public Drawable getDivider() {
3278 return mDivider;
3279 }
3280
3281 /**
3282 * Sets the drawable that will be drawn between each item in the list. If the drawable does
3283 * not have an intrinsic height, you should also call {@link #setDividerHeight(int)}
3284 *
3285 * @param divider The drawable to use.
3286 */
3287 public void setDivider(Drawable divider) {
3288 if (divider != null) {
3289 mDividerHeight = divider.getIntrinsicHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 } else {
3291 mDividerHeight = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 }
3293 mDivider = divider;
Romain Guy24443ea2009-05-11 11:56:30 -07003294 mDividerIsOpaque = divider == null || divider.getOpacity() == PixelFormat.OPAQUE;
Romain Guyeeb55e62010-12-01 18:46:07 -08003295 requestLayout();
3296 invalidate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 }
3298
3299 /**
3300 * @return Returns the height of the divider that will be drawn between each item in the list.
3301 */
3302 public int getDividerHeight() {
3303 return mDividerHeight;
3304 }
3305
3306 /**
3307 * Sets the height of the divider that will be drawn between each item in the list. Calling
3308 * this will override the intrinsic height as set by {@link #setDivider(Drawable)}
3309 *
3310 * @param height The new height of the divider in pixels.
3311 */
3312 public void setDividerHeight(int height) {
3313 mDividerHeight = height;
Romain Guyeeb55e62010-12-01 18:46:07 -08003314 requestLayout();
3315 invalidate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 }
3317
3318 /**
3319 * Enables or disables the drawing of the divider for header views.
3320 *
3321 * @param headerDividersEnabled True to draw the headers, false otherwise.
3322 *
3323 * @see #setFooterDividersEnabled(boolean)
3324 * @see #addHeaderView(android.view.View)
3325 */
3326 public void setHeaderDividersEnabled(boolean headerDividersEnabled) {
3327 mHeaderDividersEnabled = headerDividersEnabled;
3328 invalidate();
3329 }
3330
3331 /**
3332 * Enables or disables the drawing of the divider for footer views.
3333 *
3334 * @param footerDividersEnabled True to draw the footers, false otherwise.
3335 *
3336 * @see #setHeaderDividersEnabled(boolean)
3337 * @see #addFooterView(android.view.View)
3338 */
3339 public void setFooterDividersEnabled(boolean footerDividersEnabled) {
3340 mFooterDividersEnabled = footerDividersEnabled;
3341 invalidate();
3342 }
Adam Powellbfb5d4b2010-03-10 18:55:25 -08003343
Adam Powell637d3372010-08-25 14:37:03 -07003344 /**
3345 * Sets the drawable that will be drawn above all other list content.
3346 * This area can become visible when the user overscrolls the list.
3347 *
3348 * @param header The drawable to use
3349 */
3350 public void setOverscrollHeader(Drawable header) {
3351 mOverScrollHeader = header;
3352 if (mScrollY < 0) {
3353 invalidate();
3354 }
3355 }
3356
3357 /**
3358 * @return The drawable that will be drawn above all other list content
3359 */
3360 public Drawable getOverscrollHeader() {
3361 return mOverScrollHeader;
3362 }
3363
3364 /**
3365 * Sets the drawable that will be drawn below all other list content.
3366 * This area can become visible when the user overscrolls the list,
3367 * or when the list's content does not fully fill the container area.
3368 *
3369 * @param footer The drawable to use
3370 */
3371 public void setOverscrollFooter(Drawable footer) {
3372 mOverScrollFooter = footer;
3373 invalidate();
3374 }
3375
3376 /**
3377 * @return The drawable that will be drawn below all other list content
3378 */
3379 public Drawable getOverscrollFooter() {
3380 return mOverScrollFooter;
3381 }
3382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 @Override
3384 protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3385 super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
3386
Adam Powelle1bf4862011-09-02 16:56:20 -07003387 final ListAdapter adapter = mAdapter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 int closetChildIndex = -1;
Adam Powelle1bf4862011-09-02 16:56:20 -07003389 if (adapter != null && gainFocus && previouslyFocusedRect != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 previouslyFocusedRect.offset(mScrollX, mScrollY);
3391
Adam Powelld7507832010-02-18 15:40:33 -08003392 // Don't cache the result of getChildCount or mFirstPosition here,
3393 // it could change in layoutChildren.
3394 if (adapter.getCount() < getChildCount() + mFirstPosition) {
Adam Powellc854f282009-12-16 14:11:53 -08003395 mLayoutMode = LAYOUT_NORMAL;
3396 layoutChildren();
3397 }
3398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399 // figure out which item should be selected based on previously
3400 // focused rect
3401 Rect otherRect = mTempRect;
3402 int minDistance = Integer.MAX_VALUE;
3403 final int childCount = getChildCount();
Adam Powelld7507832010-02-18 15:40:33 -08003404 final int firstPosition = mFirstPosition;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405
3406 for (int i = 0; i < childCount; i++) {
3407 // only consider selectable views
3408 if (!adapter.isEnabled(firstPosition + i)) {
3409 continue;
3410 }
3411
3412 View other = getChildAt(i);
3413 other.getDrawingRect(otherRect);
3414 offsetDescendantRectToMyCoords(other, otherRect);
3415 int distance = getDistance(previouslyFocusedRect, otherRect, direction);
3416
3417 if (distance < minDistance) {
3418 minDistance = distance;
3419 closetChildIndex = i;
3420 }
3421 }
3422 }
3423
3424 if (closetChildIndex >= 0) {
3425 setSelection(closetChildIndex + mFirstPosition);
3426 } else {
3427 requestLayout();
3428 }
3429 }
3430
3431
3432 /*
3433 * (non-Javadoc)
3434 *
3435 * Children specified in XML are assumed to be header views. After we have
3436 * parsed them move them out of the children list and into mHeaderViews.
3437 */
3438 @Override
3439 protected void onFinishInflate() {
3440 super.onFinishInflate();
3441
3442 int count = getChildCount();
3443 if (count > 0) {
3444 for (int i = 0; i < count; ++i) {
3445 addHeaderView(getChildAt(i));
3446 }
3447 removeAllViews();
3448 }
3449 }
3450
3451 /* (non-Javadoc)
3452 * @see android.view.View#findViewById(int)
3453 * First look in our children, then in any header and footer views that may be scrolled off.
3454 */
3455 @Override
3456 protected View findViewTraversal(int id) {
3457 View v;
3458 v = super.findViewTraversal(id);
3459 if (v == null) {
3460 v = findViewInHeadersOrFooters(mHeaderViewInfos, id);
3461 if (v != null) {
3462 return v;
3463 }
3464 v = findViewInHeadersOrFooters(mFooterViewInfos, id);
3465 if (v != null) {
3466 return v;
3467 }
3468 }
3469 return v;
3470 }
3471
3472 /* (non-Javadoc)
3473 *
3474 * Look in the passed in list of headers or footers for the view.
3475 */
3476 View findViewInHeadersOrFooters(ArrayList<FixedViewInfo> where, int id) {
3477 if (where != null) {
3478 int len = where.size();
3479 View v;
3480
3481 for (int i = 0; i < len; i++) {
3482 v = where.get(i).view;
3483
3484 if (!v.isRootNamespace()) {
3485 v = v.findViewById(id);
3486
3487 if (v != null) {
3488 return v;
3489 }
3490 }
3491 }
3492 }
3493 return null;
3494 }
3495
3496 /* (non-Javadoc)
Jeff Brown4e6319b2010-12-13 10:36:51 -08003497 * @see android.view.View#findViewWithTag(Object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498 * First look in our children, then in any header and footer views that may be scrolled off.
3499 */
3500 @Override
3501 protected View findViewWithTagTraversal(Object tag) {
3502 View v;
3503 v = super.findViewWithTagTraversal(tag);
3504 if (v == null) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08003505 v = findViewWithTagInHeadersOrFooters(mHeaderViewInfos, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 if (v != null) {
3507 return v;
3508 }
3509
Jeff Brown4e6319b2010-12-13 10:36:51 -08003510 v = findViewWithTagInHeadersOrFooters(mFooterViewInfos, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 if (v != null) {
3512 return v;
3513 }
3514 }
3515 return v;
3516 }
3517
3518 /* (non-Javadoc)
3519 *
3520 * Look in the passed in list of headers or footers for the view with the tag.
3521 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08003522 View findViewWithTagInHeadersOrFooters(ArrayList<FixedViewInfo> where, Object tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003523 if (where != null) {
3524 int len = where.size();
3525 View v;
3526
3527 for (int i = 0; i < len; i++) {
3528 v = where.get(i).view;
3529
3530 if (!v.isRootNamespace()) {
3531 v = v.findViewWithTag(tag);
3532
3533 if (v != null) {
3534 return v;
3535 }
3536 }
3537 }
3538 }
3539 return null;
3540 }
3541
Jeff Brown4e6319b2010-12-13 10:36:51 -08003542 /**
3543 * @hide
3544 * @see android.view.View#findViewByPredicate(Predicate)
3545 * First look in our children, then in any header and footer views that may be scrolled off.
3546 */
3547 @Override
Jeff Brown4dfbec22011-08-15 14:55:37 -07003548 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08003549 View v;
Jeff Brown4dfbec22011-08-15 14:55:37 -07003550 v = super.findViewByPredicateTraversal(predicate, childToSkip);
Jeff Brown4e6319b2010-12-13 10:36:51 -08003551 if (v == null) {
Jeff Brown4dfbec22011-08-15 14:55:37 -07003552 v = findViewByPredicateInHeadersOrFooters(mHeaderViewInfos, predicate, childToSkip);
Jeff Brown4e6319b2010-12-13 10:36:51 -08003553 if (v != null) {
3554 return v;
3555 }
3556
Jeff Brown4dfbec22011-08-15 14:55:37 -07003557 v = findViewByPredicateInHeadersOrFooters(mFooterViewInfos, predicate, childToSkip);
Jeff Brown4e6319b2010-12-13 10:36:51 -08003558 if (v != null) {
3559 return v;
3560 }
3561 }
3562 return v;
3563 }
3564
3565 /* (non-Javadoc)
3566 *
3567 * Look in the passed in list of headers or footers for the first view that matches
3568 * the predicate.
3569 */
3570 View findViewByPredicateInHeadersOrFooters(ArrayList<FixedViewInfo> where,
Jeff Brown4dfbec22011-08-15 14:55:37 -07003571 Predicate<View> predicate, View childToSkip) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08003572 if (where != null) {
3573 int len = where.size();
3574 View v;
3575
3576 for (int i = 0; i < len; i++) {
3577 v = where.get(i).view;
3578
Jeff Brown4dfbec22011-08-15 14:55:37 -07003579 if (v != childToSkip && !v.isRootNamespace()) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08003580 v = v.findViewByPredicate(predicate);
3581
3582 if (v != null) {
3583 return v;
3584 }
3585 }
3586 }
3587 }
3588 return null;
3589 }
3590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003591 /**
Gilles Debunnefd3ddfa2010-02-17 16:59:20 -08003592 * Returns the set of checked items ids. The result is only valid if the
Adam Powell8f1bfe12010-03-05 15:13:56 -08003593 * choice mode has not been set to {@link #CHOICE_MODE_NONE}.
3594 *
3595 * @return A new array which contains the id of each checked item in the
3596 * list.
3597 *
Adam Powell463ceff2010-03-09 11:50:51 -08003598 * @deprecated Use {@link #getCheckedItemIds()} instead.
Adam Powell8f1bfe12010-03-05 15:13:56 -08003599 */
Adam Powell8350f7d2010-07-28 14:27:28 -07003600 @Deprecated
Adam Powell8f1bfe12010-03-05 15:13:56 -08003601 public long[] getCheckItemIds() {
Adam Powell463ceff2010-03-09 11:50:51 -08003602 // Use new behavior that correctly handles stable ID mapping.
3603 if (mAdapter != null && mAdapter.hasStableIds()) {
3604 return getCheckedItemIds();
3605 }
3606
3607 // Old behavior was buggy, but would sort of work for adapters without stable IDs.
3608 // Fall back to it to support legacy apps.
3609 if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null && mAdapter != null) {
3610 final SparseBooleanArray states = mCheckStates;
3611 final int count = states.size();
3612 final long[] ids = new long[count];
3613 final ListAdapter adapter = mAdapter;
3614
3615 int checkedCount = 0;
3616 for (int i = 0; i < count; i++) {
3617 if (states.valueAt(i)) {
3618 ids[checkedCount++] = adapter.getItemId(states.keyAt(i));
3619 }
3620 }
3621
3622 // Trim array if needed. mCheckStates may contain false values
3623 // resulting in checkedCount being smaller than count.
3624 if (checkedCount == count) {
3625 return ids;
3626 } else {
3627 final long[] result = new long[checkedCount];
3628 System.arraycopy(ids, 0, result, 0, checkedCount);
3629
3630 return result;
3631 }
3632 }
3633 return new long[0];
Adam Powell8f1bfe12010-03-05 15:13:56 -08003634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635}