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