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