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