NumberPicker.java revision fac14f9731ce7fc765de582c983af751aab697de
1/* 2 * Copyright (C) 2008 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 android.annotation.Widget; 20import android.content.Context; 21import android.content.res.ColorStateList; 22import android.content.res.TypedArray; 23import android.graphics.Canvas; 24import android.graphics.Color; 25import android.graphics.Paint; 26import android.graphics.Paint.Align; 27import android.graphics.Rect; 28import android.graphics.drawable.Drawable; 29import android.text.InputFilter; 30import android.text.InputType; 31import android.text.Spanned; 32import android.text.TextUtils; 33import android.text.method.NumberKeyListener; 34import android.util.AttributeSet; 35import android.util.SparseArray; 36import android.util.TypedValue; 37import android.view.KeyEvent; 38import android.view.LayoutInflater; 39import android.view.LayoutInflater.Filter; 40import android.view.MotionEvent; 41import android.view.VelocityTracker; 42import android.view.View; 43import android.view.ViewConfiguration; 44import android.view.accessibility.AccessibilityEvent; 45import android.view.accessibility.AccessibilityManager; 46import android.view.accessibility.AccessibilityNodeInfo; 47import android.view.accessibility.AccessibilityNodeProvider; 48import android.view.animation.DecelerateInterpolator; 49import android.view.inputmethod.EditorInfo; 50import android.view.inputmethod.InputMethodManager; 51 52import com.android.internal.R; 53 54import java.util.ArrayList; 55import java.util.Collections; 56import java.util.List; 57 58/** 59 * A widget that enables the user to select a number form a predefined range. 60 * There are two flavors of this widget and which one is presented to the user 61 * depends on the current theme. 62 * <ul> 63 * <li> 64 * If the current theme is derived from {@link android.R.style#Theme} the widget 65 * presents the current value as an editable input field with an increment button 66 * above and a decrement button below. Long pressing the buttons allows for a quick 67 * change of the current value. Tapping on the input field allows to type in 68 * a desired value. 69 * </li> 70 * <li> 71 * If the current theme is derived from {@link android.R.style#Theme_Holo} or 72 * {@link android.R.style#Theme_Holo_Light} the widget presents the current 73 * value as an editable input field with a lesser value above and a greater 74 * value below. Tapping on the lesser or greater value selects it by animating 75 * the number axis up or down to make the chosen value current. Flinging up 76 * or down allows for multiple increments or decrements of the current value. 77 * Long pressing on the lesser and greater values also allows for a quick change 78 * of the current value. Tapping on the current value allows to type in a 79 * desired value. 80 * </li> 81 * </ul> 82 * <p> 83 * For an example of using this widget, see {@link android.widget.TimePicker}. 84 * </p> 85 */ 86@Widget 87public class NumberPicker extends LinearLayout { 88 89 /** 90 * The number of items show in the selector wheel. 91 */ 92 private static final int SELECTOR_WHEEL_ITEM_COUNT = 3; 93 94 /** 95 * The default update interval during long press. 96 */ 97 private static final long DEFAULT_LONG_PRESS_UPDATE_INTERVAL = 300; 98 99 /** 100 * The index of the middle selector item. 101 */ 102 private static final int SELECTOR_MIDDLE_ITEM_INDEX = SELECTOR_WHEEL_ITEM_COUNT / 2; 103 104 /** 105 * The coefficient by which to adjust (divide) the max fling velocity. 106 */ 107 private static final int SELECTOR_MAX_FLING_VELOCITY_ADJUSTMENT = 8; 108 109 /** 110 * The the duration for adjusting the selector wheel. 111 */ 112 private static final int SELECTOR_ADJUSTMENT_DURATION_MILLIS = 800; 113 114 /** 115 * The duration of scrolling to the next/previous value while snapping to 116 * a given position. 117 */ 118 private static final int SNAP_SCROLL_DURATION = 300; 119 120 /** 121 * The strength of fading in the top and bottom while drawing the selector. 122 */ 123 private static final float TOP_AND_BOTTOM_FADING_EDGE_STRENGTH = 0.9f; 124 125 /** 126 * The default unscaled height of the selection divider. 127 */ 128 private static final int UNSCALED_DEFAULT_SELECTION_DIVIDER_HEIGHT = 2; 129 130 /** 131 * The default unscaled distance between the selection dividers. 132 */ 133 private static final int UNSCALED_DEFAULT_SELECTION_DIVIDERS_DISTANCE = 48; 134 135 /** 136 * The default unscaled minimal distance for a swipe to be considered a fling. 137 */ 138 private static final int UNSCALED_DEFAULT_MIN_FLING_DISTANCE = 150; 139 140 /** 141 * Coefficient for adjusting touch scroll distance. 142 */ 143 private static final float TOUCH_SCROLL_DECELERATION_COEFFICIENT = 2.0f; 144 145 /** 146 * The resource id for the default layout. 147 */ 148 private static final int DEFAULT_LAYOUT_RESOURCE_ID = R.layout.number_picker; 149 150 /** 151 * The numbers accepted by the input text's {@link Filter} 152 */ 153 private static final char[] DIGIT_CHARACTERS = new char[] { 154 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' 155 }; 156 157 /** 158 * Constant for unspecified size. 159 */ 160 private static final int SIZE_UNSPECIFIED = -1; 161 162 /** 163 * Use a custom NumberPicker formatting callback to use two-digit minutes 164 * strings like "01". Keeping a static formatter etc. is the most efficient 165 * way to do this; it avoids creating temporary objects on every call to 166 * format(). 167 * 168 * @hide 169 */ 170 public static final NumberPicker.Formatter TWO_DIGIT_FORMATTER = new NumberPicker.Formatter() { 171 final StringBuilder mBuilder = new StringBuilder(); 172 173 final java.util.Formatter mFmt = new java.util.Formatter(mBuilder, java.util.Locale.US); 174 175 final Object[] mArgs = new Object[1]; 176 177 public String format(int value) { 178 mArgs[0] = value; 179 mBuilder.delete(0, mBuilder.length()); 180 mFmt.format("%02d", mArgs); 181 return mFmt.toString(); 182 } 183 }; 184 185 /** 186 * The increment button. 187 */ 188 private final ImageButton mIncrementButton; 189 190 /** 191 * The decrement button. 192 */ 193 private final ImageButton mDecrementButton; 194 195 /** 196 * The text for showing the current value. 197 */ 198 private final EditText mInputText; 199 200 /** 201 * The distance between the two selection dividers. 202 */ 203 private final int mSelectionDividersDistance; 204 205 /** 206 * The min height of this widget. 207 */ 208 private final int mMinHeight; 209 210 /** 211 * The max height of this widget. 212 */ 213 private final int mMaxHeight; 214 215 /** 216 * The max width of this widget. 217 */ 218 private final int mMinWidth; 219 220 /** 221 * The max width of this widget. 222 */ 223 private int mMaxWidth; 224 225 /** 226 * Flag whether to compute the max width. 227 */ 228 private final boolean mComputeMaxWidth; 229 230 /** 231 * The height of the text. 232 */ 233 private final int mTextSize; 234 235 /** 236 * The minimal distance for a swipe to be considered a fling. 237 */ 238 private final int mMinFlingDistance; 239 240 /** 241 * The height of the gap between text elements if the selector wheel. 242 */ 243 private int mSelectorTextGapHeight; 244 245 /** 246 * The values to be displayed instead the indices. 247 */ 248 private String[] mDisplayedValues; 249 250 /** 251 * Lower value of the range of numbers allowed for the NumberPicker 252 */ 253 private int mMinValue; 254 255 /** 256 * Upper value of the range of numbers allowed for the NumberPicker 257 */ 258 private int mMaxValue; 259 260 /** 261 * Current value of this NumberPicker 262 */ 263 private int mValue; 264 265 /** 266 * Listener to be notified upon current value change. 267 */ 268 private OnValueChangeListener mOnValueChangeListener; 269 270 /** 271 * Listener to be notified upon scroll state change. 272 */ 273 private OnScrollListener mOnScrollListener; 274 275 /** 276 * Formatter for for displaying the current value. 277 */ 278 private Formatter mFormatter; 279 280 /** 281 * The speed for updating the value form long press. 282 */ 283 private long mLongPressUpdateInterval = DEFAULT_LONG_PRESS_UPDATE_INTERVAL; 284 285 /** 286 * Cache for the string representation of selector indices. 287 */ 288 private final SparseArray<String> mSelectorIndexToStringCache = new SparseArray<String>(); 289 290 /** 291 * The selector indices whose value are show by the selector. 292 */ 293 private final int[] mSelectorIndices = new int[SELECTOR_WHEEL_ITEM_COUNT]; 294 295 /** 296 * The {@link Paint} for drawing the selector. 297 */ 298 private final Paint mSelectorWheelPaint; 299 300 /** 301 * The height of a selector element (text + gap). 302 */ 303 private int mSelectorElementHeight; 304 305 /** 306 * The initial offset of the scroll selector. 307 */ 308 private int mInitialScrollOffset = Integer.MIN_VALUE; 309 310 /** 311 * The current offset of the scroll selector. 312 */ 313 private int mCurrentScrollOffset; 314 315 /** 316 * The {@link Scroller} responsible for flinging the selector. 317 */ 318 private final Scroller mFlingScroller; 319 320 /** 321 * The {@link Scroller} responsible for adjusting the selector. 322 */ 323 private final Scroller mAdjustScroller; 324 325 /** 326 * The previous Y coordinate while scrolling the selector. 327 */ 328 private int mPreviousScrollerY; 329 330 /** 331 * Handle to the reusable command for setting the input text selection. 332 */ 333 private SetSelectionCommand mSetSelectionCommand; 334 335 /** 336 * Handle to the reusable command for changing the current value from long 337 * press by one. 338 */ 339 private ChangeCurrentByOneFromLongPressCommand mChangeCurrentByOneFromLongPressCommand; 340 341 /** 342 * Command for beginning an edit of the current value via IME on long press. 343 */ 344 private BeginSoftInputOnLongPressCommand mBeginSoftInputOnLongPressCommand; 345 346 /** 347 * The Y position of the last down event. 348 */ 349 private float mLastDownEventY; 350 351 /** 352 * The time of the last down event. 353 */ 354 private long mLastDownEventTime; 355 356 /** 357 * The Y position of the last down or move event. 358 */ 359 private float mLastDownOrMoveEventY; 360 361 /** 362 * Determines speed during touch scrolling. 363 */ 364 private VelocityTracker mVelocityTracker; 365 366 /** 367 * @see ViewConfiguration#getScaledTouchSlop() 368 */ 369 private int mTouchSlop; 370 371 /** 372 * @see ViewConfiguration#getScaledMinimumFlingVelocity() 373 */ 374 private int mMinimumFlingVelocity; 375 376 /** 377 * @see ViewConfiguration#getScaledMaximumFlingVelocity() 378 */ 379 private int mMaximumFlingVelocity; 380 381 /** 382 * Flag whether the selector should wrap around. 383 */ 384 private boolean mWrapSelectorWheel; 385 386 /** 387 * The back ground color used to optimize scroller fading. 388 */ 389 private final int mSolidColor; 390 391 /** 392 * Flag whether this widget has a selector wheel. 393 */ 394 private final boolean mHasSelectorWheel; 395 396 /** 397 * Divider for showing item to be selected while scrolling 398 */ 399 private final Drawable mSelectionDivider; 400 401 /** 402 * The height of the selection divider. 403 */ 404 private final int mSelectionDividerHeight; 405 406 /** 407 * The current scroll state of the number picker. 408 */ 409 private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE; 410 411 /** 412 * Flag whether to ignore move events - we ignore such when we show in IME 413 * to prevent the content from scrolling. 414 */ 415 private boolean mIngonreMoveEvents; 416 417 /** 418 * Flag whether to show soft input on tap. 419 */ 420 private boolean mShowSoftInputOnTap; 421 422 /** 423 * The top of the top selection divider. 424 */ 425 private int mTopSelectionDividerTop; 426 427 /** 428 * The bottom of the bottom selection divider. 429 */ 430 private int mBottomSelectionDividerBottom; 431 432 /** 433 * The virtual id of the last hovered child. 434 */ 435 private int mLastHoveredChildVirtualViewId; 436 437 /** 438 * Provider to report to clients the semantic structure of this widget. 439 */ 440 private AccessibilityNodeProviderImpl mAccessibilityNodeProvider; 441 442 /** 443 * Interface to listen for changes of the current value. 444 */ 445 public interface OnValueChangeListener { 446 447 /** 448 * Called upon a change of the current value. 449 * 450 * @param picker The NumberPicker associated with this listener. 451 * @param oldVal The previous value. 452 * @param newVal The new value. 453 */ 454 void onValueChange(NumberPicker picker, int oldVal, int newVal); 455 } 456 457 /** 458 * Interface to listen for the picker scroll state. 459 */ 460 public interface OnScrollListener { 461 462 /** 463 * The view is not scrolling. 464 */ 465 public static int SCROLL_STATE_IDLE = 0; 466 467 /** 468 * The user is scrolling using touch, and his finger is still on the screen. 469 */ 470 public static int SCROLL_STATE_TOUCH_SCROLL = 1; 471 472 /** 473 * The user had previously been scrolling using touch and performed a fling. 474 */ 475 public static int SCROLL_STATE_FLING = 2; 476 477 /** 478 * Callback invoked while the number picker scroll state has changed. 479 * 480 * @param view The view whose scroll state is being reported. 481 * @param scrollState The current scroll state. One of 482 * {@link #SCROLL_STATE_IDLE}, 483 * {@link #SCROLL_STATE_TOUCH_SCROLL} or 484 * {@link #SCROLL_STATE_IDLE}. 485 */ 486 public void onScrollStateChange(NumberPicker view, int scrollState); 487 } 488 489 /** 490 * Interface used to format current value into a string for presentation. 491 */ 492 public interface Formatter { 493 494 /** 495 * Formats a string representation of the current value. 496 * 497 * @param value The currently selected value. 498 * @return A formatted string representation. 499 */ 500 public String format(int value); 501 } 502 503 /** 504 * Create a new number picker. 505 * 506 * @param context The application environment. 507 */ 508 public NumberPicker(Context context) { 509 this(context, null); 510 } 511 512 /** 513 * Create a new number picker. 514 * 515 * @param context The application environment. 516 * @param attrs A collection of attributes. 517 */ 518 public NumberPicker(Context context, AttributeSet attrs) { 519 this(context, attrs, R.attr.numberPickerStyle); 520 } 521 522 /** 523 * Create a new number picker 524 * 525 * @param context the application environment. 526 * @param attrs a collection of attributes. 527 * @param defStyle The default style to apply to this view. 528 */ 529 public NumberPicker(Context context, AttributeSet attrs, int defStyle) { 530 super(context, attrs, defStyle); 531 532 // process style attributes 533 TypedArray attributesArray = context.obtainStyledAttributes( 534 attrs, R.styleable.NumberPicker, defStyle, 0); 535 final int layoutResId = attributesArray.getResourceId( 536 R.styleable.NumberPicker_internalLayout, DEFAULT_LAYOUT_RESOURCE_ID); 537 538 mHasSelectorWheel = (layoutResId != DEFAULT_LAYOUT_RESOURCE_ID); 539 540 mSolidColor = attributesArray.getColor(R.styleable.NumberPicker_solidColor, 0); 541 542 mSelectionDivider = attributesArray.getDrawable(R.styleable.NumberPicker_selectionDivider); 543 544 final int defSelectionDividerHeight = (int) TypedValue.applyDimension( 545 TypedValue.COMPLEX_UNIT_DIP, UNSCALED_DEFAULT_SELECTION_DIVIDER_HEIGHT, 546 getResources().getDisplayMetrics()); 547 mSelectionDividerHeight = attributesArray.getDimensionPixelSize( 548 R.styleable.NumberPicker_selectionDividerHeight, defSelectionDividerHeight); 549 550 final int defSelectionDividerDistance = (int) TypedValue.applyDimension( 551 TypedValue.COMPLEX_UNIT_DIP, UNSCALED_DEFAULT_SELECTION_DIVIDERS_DISTANCE, 552 getResources().getDisplayMetrics()); 553 mSelectionDividersDistance = attributesArray.getDimensionPixelSize( 554 R.styleable.NumberPicker_selectionDividersDistance, defSelectionDividerDistance); 555 556 final int defMinFlingDistance = (int) TypedValue.applyDimension( 557 TypedValue.COMPLEX_UNIT_DIP, UNSCALED_DEFAULT_MIN_FLING_DISTANCE, 558 getResources().getDisplayMetrics()); 559 mMinFlingDistance = attributesArray.getDimensionPixelSize( 560 R.styleable.NumberPicker_minFlingDistance, defMinFlingDistance); 561 562 mMinHeight = attributesArray.getDimensionPixelSize( 563 R.styleable.NumberPicker_internalMinHeight, SIZE_UNSPECIFIED); 564 565 mMaxHeight = attributesArray.getDimensionPixelSize( 566 R.styleable.NumberPicker_internalMaxHeight, SIZE_UNSPECIFIED); 567 if (mMinHeight != SIZE_UNSPECIFIED && mMaxHeight != SIZE_UNSPECIFIED 568 && mMinHeight > mMaxHeight) { 569 throw new IllegalArgumentException("minHeight > maxHeight"); 570 } 571 572 mMinWidth = attributesArray.getDimensionPixelSize( 573 R.styleable.NumberPicker_internalMinWidth, SIZE_UNSPECIFIED); 574 575 mMaxWidth = attributesArray.getDimensionPixelSize( 576 R.styleable.NumberPicker_internalMaxWidth, SIZE_UNSPECIFIED); 577 if (mMinWidth != SIZE_UNSPECIFIED && mMaxWidth != SIZE_UNSPECIFIED 578 && mMinWidth > mMaxWidth) { 579 throw new IllegalArgumentException("minWidth > maxWidth"); 580 } 581 582 mComputeMaxWidth = (mMaxWidth == Integer.MAX_VALUE); 583 584 attributesArray.recycle(); 585 586 // By default Linearlayout that we extend is not drawn. This is 587 // its draw() method is not called but dispatchDraw() is called 588 // directly (see ViewGroup.drawChild()). However, this class uses 589 // the fading edge effect implemented by View and we need our 590 // draw() method to be called. Therefore, we declare we will draw. 591 setWillNotDraw(!mHasSelectorWheel); 592 593 LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( 594 Context.LAYOUT_INFLATER_SERVICE); 595 inflater.inflate(layoutResId, this, true); 596 597 OnClickListener onClickListener = new OnClickListener() { 598 public void onClick(View v) { 599 hideSoftInput(); 600 mInputText.clearFocus(); 601 if (v.getId() == R.id.increment) { 602 changeValueByOne(true); 603 } else { 604 changeValueByOne(false); 605 } 606 } 607 }; 608 609 OnLongClickListener onLongClickListener = new OnLongClickListener() { 610 public boolean onLongClick(View v) { 611 hideSoftInput(); 612 mInputText.clearFocus(); 613 if (v.getId() == R.id.increment) { 614 postChangeCurrentByOneFromLongPress(true, 0); 615 } else { 616 postChangeCurrentByOneFromLongPress(false, 0); 617 } 618 return true; 619 } 620 }; 621 622 // increment button 623 if (!mHasSelectorWheel) { 624 mIncrementButton = (ImageButton) findViewById(R.id.increment); 625 mIncrementButton.setOnClickListener(onClickListener); 626 mIncrementButton.setOnLongClickListener(onLongClickListener); 627 } else { 628 mIncrementButton = null; 629 } 630 631 // decrement button 632 if (!mHasSelectorWheel) { 633 mDecrementButton = (ImageButton) findViewById(R.id.decrement); 634 mDecrementButton.setOnClickListener(onClickListener); 635 mDecrementButton.setOnLongClickListener(onLongClickListener); 636 } else { 637 mDecrementButton = null; 638 } 639 640 // input text 641 mInputText = (EditText) findViewById(R.id.numberpicker_input); 642 mInputText.setOnFocusChangeListener(new OnFocusChangeListener() { 643 public void onFocusChange(View v, boolean hasFocus) { 644 if (hasFocus) { 645 mInputText.selectAll(); 646 } else { 647 mInputText.setSelection(0, 0); 648 validateInputTextView(v); 649 } 650 } 651 }); 652 mInputText.setFilters(new InputFilter[] { 653 new InputTextFilter() 654 }); 655 656 mInputText.setRawInputType(InputType.TYPE_CLASS_NUMBER); 657 mInputText.setImeOptions(EditorInfo.IME_ACTION_DONE); 658 659 // initialize constants 660 ViewConfiguration configuration = ViewConfiguration.get(context); 661 mTouchSlop = configuration.getScaledTouchSlop(); 662 mMinimumFlingVelocity = configuration.getScaledMinimumFlingVelocity(); 663 mMaximumFlingVelocity = configuration.getScaledMaximumFlingVelocity() 664 / SELECTOR_MAX_FLING_VELOCITY_ADJUSTMENT; 665 mTextSize = (int) mInputText.getTextSize(); 666 667 // create the selector wheel paint 668 Paint paint = new Paint(); 669 paint.setAntiAlias(true); 670 paint.setTextAlign(Align.CENTER); 671 paint.setTextSize(mTextSize); 672 paint.setTypeface(mInputText.getTypeface()); 673 ColorStateList colors = mInputText.getTextColors(); 674 int color = colors.getColorForState(ENABLED_STATE_SET, Color.WHITE); 675 paint.setColor(color); 676 mSelectorWheelPaint = paint; 677 678 // create the fling and adjust scrollers 679 mFlingScroller = new Scroller(getContext(), null, true); 680 mAdjustScroller = new Scroller(getContext(), new DecelerateInterpolator(2.5f)); 681 682 updateInputTextView(); 683 } 684 685 @Override 686 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 687 if (!mHasSelectorWheel) { 688 super.onLayout(changed, left, top, right, bottom); 689 return; 690 } 691 final int msrdWdth = getMeasuredWidth(); 692 final int msrdHght = getMeasuredHeight(); 693 694 // Input text centered horizontally. 695 final int inptTxtMsrdWdth = mInputText.getMeasuredWidth(); 696 final int inptTxtMsrdHght = mInputText.getMeasuredHeight(); 697 final int inptTxtLeft = (msrdWdth - inptTxtMsrdWdth) / 2; 698 final int inptTxtTop = (msrdHght - inptTxtMsrdHght) / 2; 699 final int inptTxtRight = inptTxtLeft + inptTxtMsrdWdth; 700 final int inptTxtBottom = inptTxtTop + inptTxtMsrdHght; 701 mInputText.layout(inptTxtLeft, inptTxtTop, inptTxtRight, inptTxtBottom); 702 703 if (changed) { 704 // need to do all this when we know our size 705 initializeSelectorWheel(); 706 initializeFadingEdges(); 707 mTopSelectionDividerTop = (getHeight() - mSelectionDividersDistance) / 2 708 - mSelectionDividerHeight; 709 mBottomSelectionDividerBottom = mTopSelectionDividerTop + 2 * mSelectionDividerHeight 710 + mSelectionDividersDistance; 711 } 712 } 713 714 @Override 715 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 716 if (!mHasSelectorWheel) { 717 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 718 return; 719 } 720 // Try greedily to fit the max width and height. 721 final int newWidthMeasureSpec = makeMeasureSpec(widthMeasureSpec, mMaxWidth); 722 final int newHeightMeasureSpec = makeMeasureSpec(heightMeasureSpec, mMaxHeight); 723 super.onMeasure(newWidthMeasureSpec, newHeightMeasureSpec); 724 // Flag if we are measured with width or height less than the respective min. 725 final int widthSize = resolveSizeAndStateRespectingMinSize(mMinWidth, getMeasuredWidth(), 726 widthMeasureSpec); 727 final int heightSize = resolveSizeAndStateRespectingMinSize(mMinHeight, getMeasuredHeight(), 728 heightMeasureSpec); 729 setMeasuredDimension(widthSize, heightSize); 730 } 731 732 /** 733 * Move to the final position of a scroller. Ensures to force finish the scroller 734 * and if it is not at its final position a scroll of the selector wheel is 735 * performed to fast forward to the final position. 736 * 737 * @param scroller The scroller to whose final position to get. 738 * @return True of the a move was performed, i.e. the scroller was not in final position. 739 */ 740 private boolean moveToFinalScrollerPosition(Scroller scroller) { 741 scroller.forceFinished(true); 742 int amountToScroll = scroller.getFinalY() - scroller.getCurrY(); 743 int futureScrollOffset = (mCurrentScrollOffset + amountToScroll) % mSelectorElementHeight; 744 int overshootAdjustment = mInitialScrollOffset - futureScrollOffset; 745 if (overshootAdjustment != 0) { 746 if (Math.abs(overshootAdjustment) > mSelectorElementHeight / 2) { 747 if (overshootAdjustment > 0) { 748 overshootAdjustment -= mSelectorElementHeight; 749 } else { 750 overshootAdjustment += mSelectorElementHeight; 751 } 752 } 753 amountToScroll += overshootAdjustment; 754 scrollBy(0, amountToScroll); 755 return true; 756 } 757 return false; 758 } 759 760 @Override 761 public boolean onInterceptTouchEvent(MotionEvent event) { 762 if (!mHasSelectorWheel || !isEnabled()) { 763 return false; 764 } 765 final int action = event.getActionMasked(); 766 switch (action) { 767 case MotionEvent.ACTION_DOWN: { 768 removeAllCallbacks(); 769 mInputText.setVisibility(View.INVISIBLE); 770 mLastDownOrMoveEventY = mLastDownEventY = event.getY(); 771 mLastDownEventTime = event.getEventTime(); 772 mIngonreMoveEvents = false; 773 mShowSoftInputOnTap = false; 774 if (!mFlingScroller.isFinished()) { 775 mFlingScroller.forceFinished(true); 776 mAdjustScroller.forceFinished(true); 777 onScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); 778 } else if (!mAdjustScroller.isFinished()) { 779 mFlingScroller.forceFinished(true); 780 mAdjustScroller.forceFinished(true); 781 } else if (mLastDownEventY < mTopSelectionDividerTop) { 782 hideSoftInput(); 783 postChangeCurrentByOneFromLongPress( 784 false, ViewConfiguration.getLongPressTimeout()); 785 } else if (mLastDownEventY > mBottomSelectionDividerBottom) { 786 hideSoftInput(); 787 postChangeCurrentByOneFromLongPress( 788 true, ViewConfiguration.getLongPressTimeout()); 789 } else { 790 mShowSoftInputOnTap = true; 791 postBeginSoftInputOnLongPressCommand(); 792 } 793 return true; 794 } 795 } 796 return false; 797 } 798 799 @Override 800 public boolean onTouchEvent(MotionEvent event) { 801 if (!isEnabled() || !mHasSelectorWheel) { 802 return false; 803 } 804 if (mVelocityTracker == null) { 805 mVelocityTracker = VelocityTracker.obtain(); 806 } 807 mVelocityTracker.addMovement(event); 808 int action = event.getActionMasked(); 809 switch (action) { 810 case MotionEvent.ACTION_MOVE: { 811 if (mIngonreMoveEvents) { 812 break; 813 } 814 float currentMoveY = event.getY(); 815 if (mScrollState != OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { 816 int deltaDownY = (int) Math.abs(currentMoveY - mLastDownEventY); 817 if (deltaDownY > mTouchSlop) { 818 removeAllCallbacks(); 819 onScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL); 820 } 821 } else { 822 int deltaMoveY = (int) ((currentMoveY - mLastDownOrMoveEventY) 823 / TOUCH_SCROLL_DECELERATION_COEFFICIENT); 824 scrollBy(0, deltaMoveY); 825 invalidate(); 826 } 827 mLastDownOrMoveEventY = currentMoveY; 828 } break; 829 case MotionEvent.ACTION_UP: { 830 removeBeginSoftInputCommand(); 831 removeChangeCurrentByOneFromLongPress(); 832 VelocityTracker velocityTracker = mVelocityTracker; 833 velocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity); 834 int initialVelocity = (int) velocityTracker.getYVelocity(); 835 if (Math.abs(initialVelocity) > mMinimumFlingVelocity) { 836 int deltaMove = (int) (event.getY() - mLastDownEventY); 837 int absDeltaMoveY = Math.abs(deltaMove); 838 if (absDeltaMoveY > mMinFlingDistance) { 839 fling(initialVelocity); 840 } else { 841 final int normalizedDeltaMove = 842 (int) (absDeltaMoveY / TOUCH_SCROLL_DECELERATION_COEFFICIENT); 843 if (normalizedDeltaMove < mSelectorElementHeight) { 844 snapToNextValue(deltaMove < 0); 845 } else { 846 snapToClosestValue(); 847 } 848 } 849 onScrollStateChange(OnScrollListener.SCROLL_STATE_FLING); 850 } else { 851 int eventY = (int) event.getY(); 852 int deltaMoveY = (int) Math.abs(eventY - mLastDownEventY); 853 long deltaTime = event.getEventTime() - mLastDownEventTime; 854 if (deltaMoveY <= mTouchSlop && deltaTime < ViewConfiguration.getTapTimeout()) { 855 if (mShowSoftInputOnTap) { 856 mShowSoftInputOnTap = false; 857 showSoftInput(); 858 } else { 859 int selectorIndexOffset = (eventY / mSelectorElementHeight) 860 - SELECTOR_MIDDLE_ITEM_INDEX; 861 if (selectorIndexOffset > 0) { 862 changeValueByOne(true); 863 } else if (selectorIndexOffset < 0) { 864 changeValueByOne(false); 865 } 866 } 867 } else { 868 ensureScrollWheelAdjusted(); 869 } 870 onScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); 871 } 872 mVelocityTracker.recycle(); 873 mVelocityTracker = null; 874 } break; 875 } 876 return true; 877 } 878 879 @Override 880 public boolean dispatchTouchEvent(MotionEvent event) { 881 final int action = event.getActionMasked(); 882 switch (action) { 883 case MotionEvent.ACTION_CANCEL: 884 case MotionEvent.ACTION_UP: 885 removeAllCallbacks(); 886 break; 887 } 888 return super.dispatchTouchEvent(event); 889 } 890 891 @Override 892 public boolean dispatchKeyEvent(KeyEvent event) { 893 final int keyCode = event.getKeyCode(); 894 switch (keyCode) { 895 case KeyEvent.KEYCODE_DPAD_CENTER: 896 case KeyEvent.KEYCODE_ENTER: 897 removeAllCallbacks(); 898 break; 899 } 900 return super.dispatchKeyEvent(event); 901 } 902 903 @Override 904 public boolean dispatchTrackballEvent(MotionEvent event) { 905 final int action = event.getActionMasked(); 906 switch (action) { 907 case MotionEvent.ACTION_CANCEL: 908 case MotionEvent.ACTION_UP: 909 removeAllCallbacks(); 910 break; 911 } 912 return super.dispatchTrackballEvent(event); 913 } 914 915 @Override 916 protected boolean dispatchHoverEvent(MotionEvent event) { 917 if (!mHasSelectorWheel) { 918 return super.dispatchHoverEvent(event); 919 } 920 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 921 final int eventY = (int) event.getY(); 922 final int hoveredVirtualViewId; 923 if (eventY < mTopSelectionDividerTop) { 924 hoveredVirtualViewId = AccessibilityNodeProviderImpl.VIRTUAL_VIEW_ID_DECREMENT; 925 } else if (eventY > mBottomSelectionDividerBottom) { 926 hoveredVirtualViewId = AccessibilityNodeProviderImpl.VIRTUAL_VIEW_ID_INCREMENT; 927 } else { 928 hoveredVirtualViewId = AccessibilityNodeProviderImpl.VIRTUAL_VIEW_ID_INPUT; 929 } 930 final int action = event.getActionMasked(); 931 AccessibilityNodeProviderImpl provider = 932 (AccessibilityNodeProviderImpl) getAccessibilityNodeProvider(); 933 switch (action) { 934 case MotionEvent.ACTION_HOVER_ENTER: { 935 provider.sendAccessibilityEventForVirtualView(hoveredVirtualViewId, 936 AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 937 mLastHoveredChildVirtualViewId = hoveredVirtualViewId; 938 } break; 939 case MotionEvent.ACTION_HOVER_MOVE: { 940 if (mLastHoveredChildVirtualViewId != hoveredVirtualViewId 941 && mLastHoveredChildVirtualViewId != View.NO_ID) { 942 provider.sendAccessibilityEventForVirtualView( 943 mLastHoveredChildVirtualViewId, 944 AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 945 provider.sendAccessibilityEventForVirtualView(hoveredVirtualViewId, 946 AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 947 mLastHoveredChildVirtualViewId = hoveredVirtualViewId; 948 } 949 } break; 950 case MotionEvent.ACTION_HOVER_EXIT: { 951 provider.sendAccessibilityEventForVirtualView(hoveredVirtualViewId, 952 AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 953 mLastHoveredChildVirtualViewId = View.NO_ID; 954 } break; 955 } 956 } 957 return false; 958 } 959 960 @Override 961 public void computeScroll() { 962 Scroller scroller = mFlingScroller; 963 if (scroller.isFinished()) { 964 scroller = mAdjustScroller; 965 if (scroller.isFinished()) { 966 return; 967 } 968 } 969 scroller.computeScrollOffset(); 970 int currentScrollerY = scroller.getCurrY(); 971 if (mPreviousScrollerY == 0) { 972 mPreviousScrollerY = scroller.getStartY(); 973 } 974 scrollBy(0, currentScrollerY - mPreviousScrollerY); 975 mPreviousScrollerY = currentScrollerY; 976 if (scroller.isFinished()) { 977 onScrollerFinished(scroller); 978 } else { 979 invalidate(); 980 } 981 } 982 983 @Override 984 public void setEnabled(boolean enabled) { 985 super.setEnabled(enabled); 986 if (!mHasSelectorWheel) { 987 mIncrementButton.setEnabled(enabled); 988 } 989 if (!mHasSelectorWheel) { 990 mDecrementButton.setEnabled(enabled); 991 } 992 mInputText.setEnabled(enabled); 993 } 994 995 @Override 996 public void scrollBy(int x, int y) { 997 int[] selectorIndices = mSelectorIndices; 998 if (!mWrapSelectorWheel && y > 0 999 && selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX] <= mMinValue) { 1000 mCurrentScrollOffset = mInitialScrollOffset; 1001 return; 1002 } 1003 if (!mWrapSelectorWheel && y < 0 1004 && selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX] >= mMaxValue) { 1005 mCurrentScrollOffset = mInitialScrollOffset; 1006 return; 1007 } 1008 mCurrentScrollOffset += y; 1009 while (mCurrentScrollOffset - mInitialScrollOffset > mSelectorTextGapHeight) { 1010 mCurrentScrollOffset -= mSelectorElementHeight; 1011 decrementSelectorIndices(selectorIndices); 1012 setValueInternal(selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX], true); 1013 if (!mWrapSelectorWheel && selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX] <= mMinValue) { 1014 mCurrentScrollOffset = mInitialScrollOffset; 1015 } 1016 } 1017 while (mCurrentScrollOffset - mInitialScrollOffset < -mSelectorTextGapHeight) { 1018 mCurrentScrollOffset += mSelectorElementHeight; 1019 incrementSelectorIndices(selectorIndices); 1020 setValueInternal(selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX], true); 1021 if (!mWrapSelectorWheel && selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX] >= mMaxValue) { 1022 mCurrentScrollOffset = mInitialScrollOffset; 1023 } 1024 } 1025 } 1026 1027 @Override 1028 public int getSolidColor() { 1029 return mSolidColor; 1030 } 1031 1032 /** 1033 * Sets the listener to be notified on change of the current value. 1034 * 1035 * @param onValueChangedListener The listener. 1036 */ 1037 public void setOnValueChangedListener(OnValueChangeListener onValueChangedListener) { 1038 mOnValueChangeListener = onValueChangedListener; 1039 } 1040 1041 /** 1042 * Set listener to be notified for scroll state changes. 1043 * 1044 * @param onScrollListener The listener. 1045 */ 1046 public void setOnScrollListener(OnScrollListener onScrollListener) { 1047 mOnScrollListener = onScrollListener; 1048 } 1049 1050 /** 1051 * Set the formatter to be used for formatting the current value. 1052 * <p> 1053 * Note: If you have provided alternative values for the values this 1054 * formatter is never invoked. 1055 * </p> 1056 * 1057 * @param formatter The formatter object. If formatter is <code>null</code>, 1058 * {@link String#valueOf(int)} will be used. 1059 *@see #setDisplayedValues(String[]) 1060 */ 1061 public void setFormatter(Formatter formatter) { 1062 if (formatter == mFormatter) { 1063 return; 1064 } 1065 mFormatter = formatter; 1066 initializeSelectorWheelIndices(); 1067 updateInputTextView(); 1068 } 1069 1070 /** 1071 * Set the current value for the number picker. 1072 * <p> 1073 * If the argument is less than the {@link NumberPicker#getMinValue()} and 1074 * {@link NumberPicker#getWrapSelectorWheel()} is <code>false</code> the 1075 * current value is set to the {@link NumberPicker#getMinValue()} value. 1076 * </p> 1077 * <p> 1078 * If the argument is less than the {@link NumberPicker#getMinValue()} and 1079 * {@link NumberPicker#getWrapSelectorWheel()} is <code>true</code> the 1080 * current value is set to the {@link NumberPicker#getMaxValue()} value. 1081 * </p> 1082 * <p> 1083 * If the argument is less than the {@link NumberPicker#getMaxValue()} and 1084 * {@link NumberPicker#getWrapSelectorWheel()} is <code>false</code> the 1085 * current value is set to the {@link NumberPicker#getMaxValue()} value. 1086 * </p> 1087 * <p> 1088 * If the argument is less than the {@link NumberPicker#getMaxValue()} and 1089 * {@link NumberPicker#getWrapSelectorWheel()} is <code>true</code> the 1090 * current value is set to the {@link NumberPicker#getMinValue()} value. 1091 * </p> 1092 * 1093 * @param value The current value. 1094 * @see #setWrapSelectorWheel(boolean) 1095 * @see #setMinValue(int) 1096 * @see #setMaxValue(int) 1097 */ 1098 public void setValue(int value) { 1099 setValueInternal(value, false); 1100 } 1101 1102 /** 1103 * Shows the soft input for its input text. 1104 */ 1105 private void showSoftInput() { 1106 InputMethodManager inputMethodManager = InputMethodManager.peekInstance(); 1107 if (inputMethodManager != null) { 1108 if (mHasSelectorWheel) { 1109 mInputText.setVisibility(View.VISIBLE); 1110 } 1111 mInputText.requestFocus(); 1112 inputMethodManager.showSoftInput(mInputText, 0); 1113 } 1114 } 1115 1116 /** 1117 * Hides the soft input if it is active for the input text. 1118 */ 1119 private void hideSoftInput() { 1120 InputMethodManager inputMethodManager = InputMethodManager.peekInstance(); 1121 if (inputMethodManager != null && inputMethodManager.isActive(mInputText)) { 1122 inputMethodManager.hideSoftInputFromWindow(getWindowToken(), 0); 1123 if (mHasSelectorWheel) { 1124 mInputText.setVisibility(View.INVISIBLE); 1125 } 1126 } 1127 } 1128 1129 /** 1130 * Computes the max width if no such specified as an attribute. 1131 */ 1132 private void tryComputeMaxWidth() { 1133 if (!mComputeMaxWidth) { 1134 return; 1135 } 1136 int maxTextWidth = 0; 1137 if (mDisplayedValues == null) { 1138 float maxDigitWidth = 0; 1139 for (int i = 0; i <= 9; i++) { 1140 final float digitWidth = mSelectorWheelPaint.measureText(String.valueOf(i)); 1141 if (digitWidth > maxDigitWidth) { 1142 maxDigitWidth = digitWidth; 1143 } 1144 } 1145 int numberOfDigits = 0; 1146 int current = mMaxValue; 1147 while (current > 0) { 1148 numberOfDigits++; 1149 current = current / 10; 1150 } 1151 maxTextWidth = (int) (numberOfDigits * maxDigitWidth); 1152 } else { 1153 final int valueCount = mDisplayedValues.length; 1154 for (int i = 0; i < valueCount; i++) { 1155 final float textWidth = mSelectorWheelPaint.measureText(mDisplayedValues[i]); 1156 if (textWidth > maxTextWidth) { 1157 maxTextWidth = (int) textWidth; 1158 } 1159 } 1160 } 1161 maxTextWidth += mInputText.getPaddingLeft() + mInputText.getPaddingRight(); 1162 if (mMaxWidth != maxTextWidth) { 1163 if (maxTextWidth > mMinWidth) { 1164 mMaxWidth = maxTextWidth; 1165 } else { 1166 mMaxWidth = mMinWidth; 1167 } 1168 invalidate(); 1169 } 1170 } 1171 1172 /** 1173 * Gets whether the selector wheel wraps when reaching the min/max value. 1174 * 1175 * @return True if the selector wheel wraps. 1176 * 1177 * @see #getMinValue() 1178 * @see #getMaxValue() 1179 */ 1180 public boolean getWrapSelectorWheel() { 1181 return mWrapSelectorWheel; 1182 } 1183 1184 /** 1185 * Sets whether the selector wheel shown during flinging/scrolling should 1186 * wrap around the {@link NumberPicker#getMinValue()} and 1187 * {@link NumberPicker#getMaxValue()} values. 1188 * <p> 1189 * By default if the range (max - min) is more than the number of items shown 1190 * on the selector wheel the selector wheel wrapping is enabled. 1191 * </p> 1192 * <p> 1193 * <strong>Note:</strong> If the number of items, i.e. the range ( 1194 * {@link #getMaxValue()} - {@link #getMinValue()}) is less than 1195 * the number of items shown on the selector wheel, the selector wheel will 1196 * not wrap. Hence, in such a case calling this method is a NOP. 1197 * </p> 1198 * 1199 * @param wrapSelectorWheel Whether to wrap. 1200 */ 1201 public void setWrapSelectorWheel(boolean wrapSelectorWheel) { 1202 final boolean wrappingAllowed = (mMaxValue - mMinValue) >= mSelectorIndices.length; 1203 if ((!wrapSelectorWheel || wrappingAllowed) && wrapSelectorWheel != mWrapSelectorWheel) { 1204 mWrapSelectorWheel = wrapSelectorWheel; 1205 } 1206 } 1207 1208 /** 1209 * Sets the speed at which the numbers be incremented and decremented when 1210 * the up and down buttons are long pressed respectively. 1211 * <p> 1212 * The default value is 300 ms. 1213 * </p> 1214 * 1215 * @param intervalMillis The speed (in milliseconds) at which the numbers 1216 * will be incremented and decremented. 1217 */ 1218 public void setOnLongPressUpdateInterval(long intervalMillis) { 1219 mLongPressUpdateInterval = intervalMillis; 1220 } 1221 1222 /** 1223 * Returns the value of the picker. 1224 * 1225 * @return The value. 1226 */ 1227 public int getValue() { 1228 return mValue; 1229 } 1230 1231 /** 1232 * Returns the min value of the picker. 1233 * 1234 * @return The min value 1235 */ 1236 public int getMinValue() { 1237 return mMinValue; 1238 } 1239 1240 /** 1241 * Sets the min value of the picker. 1242 * 1243 * @param minValue The min value. 1244 */ 1245 public void setMinValue(int minValue) { 1246 if (mMinValue == minValue) { 1247 return; 1248 } 1249 if (minValue < 0) { 1250 throw new IllegalArgumentException("minValue must be >= 0"); 1251 } 1252 mMinValue = minValue; 1253 if (mMinValue > mValue) { 1254 mValue = mMinValue; 1255 } 1256 boolean wrapSelectorWheel = mMaxValue - mMinValue > mSelectorIndices.length; 1257 setWrapSelectorWheel(wrapSelectorWheel); 1258 initializeSelectorWheelIndices(); 1259 updateInputTextView(); 1260 tryComputeMaxWidth(); 1261 invalidate(); 1262 } 1263 1264 /** 1265 * Returns the max value of the picker. 1266 * 1267 * @return The max value. 1268 */ 1269 public int getMaxValue() { 1270 return mMaxValue; 1271 } 1272 1273 /** 1274 * Sets the max value of the picker. 1275 * 1276 * @param maxValue The max value. 1277 */ 1278 public void setMaxValue(int maxValue) { 1279 if (mMaxValue == maxValue) { 1280 return; 1281 } 1282 if (maxValue < 0) { 1283 throw new IllegalArgumentException("maxValue must be >= 0"); 1284 } 1285 mMaxValue = maxValue; 1286 if (mMaxValue < mValue) { 1287 mValue = mMaxValue; 1288 } 1289 boolean wrapSelectorWheel = mMaxValue - mMinValue > mSelectorIndices.length; 1290 setWrapSelectorWheel(wrapSelectorWheel); 1291 initializeSelectorWheelIndices(); 1292 updateInputTextView(); 1293 tryComputeMaxWidth(); 1294 invalidate(); 1295 } 1296 1297 /** 1298 * Gets the values to be displayed instead of string values. 1299 * 1300 * @return The displayed values. 1301 */ 1302 public String[] getDisplayedValues() { 1303 return mDisplayedValues; 1304 } 1305 1306 /** 1307 * Sets the values to be displayed. 1308 * 1309 * @param displayedValues The displayed values. 1310 */ 1311 public void setDisplayedValues(String[] displayedValues) { 1312 if (mDisplayedValues == displayedValues) { 1313 return; 1314 } 1315 mDisplayedValues = displayedValues; 1316 if (mDisplayedValues != null) { 1317 // Allow text entry rather than strictly numeric entry. 1318 mInputText.setRawInputType(InputType.TYPE_CLASS_TEXT 1319 | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); 1320 } else { 1321 mInputText.setRawInputType(InputType.TYPE_CLASS_NUMBER); 1322 } 1323 updateInputTextView(); 1324 initializeSelectorWheelIndices(); 1325 tryComputeMaxWidth(); 1326 } 1327 1328 @Override 1329 protected float getTopFadingEdgeStrength() { 1330 return TOP_AND_BOTTOM_FADING_EDGE_STRENGTH; 1331 } 1332 1333 @Override 1334 protected float getBottomFadingEdgeStrength() { 1335 return TOP_AND_BOTTOM_FADING_EDGE_STRENGTH; 1336 } 1337 1338 @Override 1339 protected void onDetachedFromWindow() { 1340 removeAllCallbacks(); 1341 } 1342 1343 @Override 1344 protected void onDraw(Canvas canvas) { 1345 if (!mHasSelectorWheel) { 1346 super.onDraw(canvas); 1347 return; 1348 } 1349 float x = (mRight - mLeft) / 2; 1350 float y = mCurrentScrollOffset; 1351 1352 // draw the selector wheel 1353 int[] selectorIndices = mSelectorIndices; 1354 for (int i = 0; i < selectorIndices.length; i++) { 1355 int selectorIndex = selectorIndices[i]; 1356 String scrollSelectorValue = mSelectorIndexToStringCache.get(selectorIndex); 1357 // Do not draw the middle item if input is visible since the input 1358 // is shown only if the wheel is static and it covers the middle 1359 // item. Otherwise, if the user starts editing the text via the 1360 // IME he may see a dimmed version of the old value intermixed 1361 // with the new one. 1362 if (i != SELECTOR_MIDDLE_ITEM_INDEX || mInputText.getVisibility() != VISIBLE) { 1363 canvas.drawText(scrollSelectorValue, x, y, mSelectorWheelPaint); 1364 } 1365 y += mSelectorElementHeight; 1366 } 1367 1368 // draw the selection dividers 1369 if (mSelectionDivider != null) { 1370 // draw the top divider 1371 int topOfTopDivider = mTopSelectionDividerTop; 1372 int bottomOfTopDivider = topOfTopDivider + mSelectionDividerHeight; 1373 mSelectionDivider.setBounds(0, topOfTopDivider, mRight, bottomOfTopDivider); 1374 mSelectionDivider.draw(canvas); 1375 1376 // draw the bottom divider 1377 int bottomOfBottomDivider = mBottomSelectionDividerBottom; 1378 int topOfBottomDivider = bottomOfBottomDivider - mSelectionDividerHeight; 1379 mSelectionDivider.setBounds(0, topOfBottomDivider, mRight, bottomOfBottomDivider); 1380 mSelectionDivider.draw(canvas); 1381 } 1382 } 1383 1384 @Override 1385 public void sendAccessibilityEvent(int eventType) { 1386 // Do not send accessibility events - we want the user to 1387 // perceive this widget as several controls rather as a whole. 1388 } 1389 1390 @Override 1391 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 1392 super.onInitializeAccessibilityEvent(event); 1393 event.setClassName(NumberPicker.class.getName()); 1394 event.setScrollable(true); 1395 event.setScrollY((mMinValue + mValue) * mSelectorElementHeight); 1396 event.setMaxScrollY((mMaxValue - mMinValue) * mSelectorElementHeight); 1397 } 1398 1399 @Override 1400 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 1401 if (!mHasSelectorWheel) { 1402 return super.getAccessibilityNodeProvider(); 1403 } 1404 if (mAccessibilityNodeProvider == null) { 1405 mAccessibilityNodeProvider = new AccessibilityNodeProviderImpl(); 1406 } 1407 return mAccessibilityNodeProvider; 1408 } 1409 1410 /** 1411 * Makes a measure spec that tries greedily to use the max value. 1412 * 1413 * @param measureSpec The measure spec. 1414 * @param maxSize The max value for the size. 1415 * @return A measure spec greedily imposing the max size. 1416 */ 1417 private int makeMeasureSpec(int measureSpec, int maxSize) { 1418 if (maxSize == SIZE_UNSPECIFIED) { 1419 return measureSpec; 1420 } 1421 final int size = MeasureSpec.getSize(measureSpec); 1422 final int mode = MeasureSpec.getMode(measureSpec); 1423 switch (mode) { 1424 case MeasureSpec.EXACTLY: 1425 return measureSpec; 1426 case MeasureSpec.AT_MOST: 1427 return MeasureSpec.makeMeasureSpec(Math.min(size, maxSize), MeasureSpec.EXACTLY); 1428 case MeasureSpec.UNSPECIFIED: 1429 return MeasureSpec.makeMeasureSpec(maxSize, MeasureSpec.EXACTLY); 1430 default: 1431 throw new IllegalArgumentException("Unknown measure mode: " + mode); 1432 } 1433 } 1434 1435 /** 1436 * Utility to reconcile a desired size and state, with constraints imposed 1437 * by a MeasureSpec. Tries to respect the min size, unless a different size 1438 * is imposed by the constraints. 1439 * 1440 * @param minSize The minimal desired size. 1441 * @param measuredSize The currently measured size. 1442 * @param measureSpec The current measure spec. 1443 * @return The resolved size and state. 1444 */ 1445 private int resolveSizeAndStateRespectingMinSize( 1446 int minSize, int measuredSize, int measureSpec) { 1447 if (minSize != SIZE_UNSPECIFIED) { 1448 final int desiredWidth = Math.max(minSize, measuredSize); 1449 return resolveSizeAndState(desiredWidth, measureSpec, 0); 1450 } else { 1451 return measuredSize; 1452 } 1453 } 1454 1455 /** 1456 * Resets the selector indices and clear the cached string representation of 1457 * these indices. 1458 */ 1459 private void initializeSelectorWheelIndices() { 1460 mSelectorIndexToStringCache.clear(); 1461 int[] selectorIdices = mSelectorIndices; 1462 int current = getValue(); 1463 for (int i = 0; i < mSelectorIndices.length; i++) { 1464 int selectorIndex = current + (i - SELECTOR_MIDDLE_ITEM_INDEX); 1465 if (mWrapSelectorWheel) { 1466 selectorIndex = getWrappedSelectorIndex(selectorIndex); 1467 } 1468 mSelectorIndices[i] = selectorIndex; 1469 ensureCachedScrollSelectorValue(mSelectorIndices[i]); 1470 } 1471 } 1472 1473 /** 1474 * Sets the current value of this NumberPicker. 1475 * 1476 * @param current The new value of the NumberPicker. 1477 * @param notifyChange Whether to notify if the current value changed. 1478 */ 1479 private void setValueInternal(int current, boolean notifyChange) { 1480 if (mValue == current) { 1481 return; 1482 } 1483 // Wrap around the values if we go past the start or end 1484 if (mWrapSelectorWheel) { 1485 current = getWrappedSelectorIndex(current); 1486 } else { 1487 current = Math.max(current, mMinValue); 1488 current = Math.min(current, mMaxValue); 1489 } 1490 int previous = mValue; 1491 mValue = current; 1492 updateInputTextView(); 1493 if (notifyChange) { 1494 notifyChange(previous, current); 1495 } 1496 initializeSelectorWheelIndices(); 1497 invalidate(); 1498 } 1499 1500 /** 1501 * Changes the current value by one which is increment or 1502 * decrement based on the passes argument. 1503 * decrement the current value. 1504 * 1505 * @param increment True to increment, false to decrement. 1506 */ 1507 private void changeValueByOne(boolean increment) { 1508 if (mHasSelectorWheel) { 1509 mInputText.setVisibility(View.INVISIBLE); 1510 if (!moveToFinalScrollerPosition(mFlingScroller)) { 1511 moveToFinalScrollerPosition(mAdjustScroller); 1512 } 1513 mPreviousScrollerY = 0; 1514 if (increment) { 1515 mFlingScroller.startScroll(0, 0, 0, -mSelectorElementHeight, SNAP_SCROLL_DURATION); 1516 } else { 1517 mFlingScroller.startScroll(0, 0, 0, mSelectorElementHeight, SNAP_SCROLL_DURATION); 1518 } 1519 invalidate(); 1520 } else { 1521 if (increment) { 1522 setValueInternal(mValue + 1, true); 1523 } else { 1524 setValueInternal(mValue - 1, true); 1525 } 1526 } 1527 } 1528 1529 private void initializeSelectorWheel() { 1530 initializeSelectorWheelIndices(); 1531 int[] selectorIndices = mSelectorIndices; 1532 int totalTextHeight = selectorIndices.length * mTextSize; 1533 float totalTextGapHeight = (mBottom - mTop) - totalTextHeight; 1534 float textGapCount = selectorIndices.length; 1535 mSelectorTextGapHeight = (int) (totalTextGapHeight / textGapCount + 0.5f); 1536 mSelectorElementHeight = mTextSize + mSelectorTextGapHeight; 1537 // Ensure that the middle item is positioned the same as the text in 1538 // mInputText 1539 int editTextTextPosition = mInputText.getBaseline() + mInputText.getTop(); 1540 mInitialScrollOffset = editTextTextPosition 1541 - (mSelectorElementHeight * SELECTOR_MIDDLE_ITEM_INDEX); 1542 mCurrentScrollOffset = mInitialScrollOffset; 1543 updateInputTextView(); 1544 } 1545 1546 private void initializeFadingEdges() { 1547 setVerticalFadingEdgeEnabled(true); 1548 setFadingEdgeLength((mBottom - mTop - mTextSize) / 2); 1549 } 1550 1551 /** 1552 * Callback invoked upon completion of a given <code>scroller</code>. 1553 */ 1554 private void onScrollerFinished(Scroller scroller) { 1555 if (scroller == mFlingScroller) { 1556 if (!ensureScrollWheelAdjusted()) { 1557 updateInputTextView(); 1558 } 1559 onScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); 1560 } else { 1561 if (mScrollState != OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { 1562 updateInputTextView(); 1563 } 1564 } 1565 } 1566 1567 /** 1568 * Handles transition to a given <code>scrollState</code> 1569 */ 1570 private void onScrollStateChange(int scrollState) { 1571 if (mScrollState == scrollState) { 1572 return; 1573 } 1574 mScrollState = scrollState; 1575 if (mOnScrollListener != null) { 1576 mOnScrollListener.onScrollStateChange(this, scrollState); 1577 } 1578 } 1579 1580 /** 1581 * Flings the selector with the given <code>velocityY</code>. 1582 */ 1583 private void fling(int velocityY) { 1584 mPreviousScrollerY = 0; 1585 1586 if (velocityY > 0) { 1587 mFlingScroller.fling(0, 0, 0, velocityY, 0, 0, 0, Integer.MAX_VALUE); 1588 } else { 1589 mFlingScroller.fling(0, Integer.MAX_VALUE, 0, velocityY, 0, 0, 0, Integer.MAX_VALUE); 1590 } 1591 1592 invalidate(); 1593 } 1594 1595 /** 1596 * @return The wrapped index <code>selectorIndex</code> value. 1597 */ 1598 private int getWrappedSelectorIndex(int selectorIndex) { 1599 if (selectorIndex > mMaxValue) { 1600 return mMinValue + (selectorIndex - mMaxValue) % (mMaxValue - mMinValue) - 1; 1601 } else if (selectorIndex < mMinValue) { 1602 return mMaxValue - (mMinValue - selectorIndex) % (mMaxValue - mMinValue) + 1; 1603 } 1604 return selectorIndex; 1605 } 1606 1607 /** 1608 * Increments the <code>selectorIndices</code> whose string representations 1609 * will be displayed in the selector. 1610 */ 1611 private void incrementSelectorIndices(int[] selectorIndices) { 1612 for (int i = 0; i < selectorIndices.length - 1; i++) { 1613 selectorIndices[i] = selectorIndices[i + 1]; 1614 } 1615 int nextScrollSelectorIndex = selectorIndices[selectorIndices.length - 2] + 1; 1616 if (mWrapSelectorWheel && nextScrollSelectorIndex > mMaxValue) { 1617 nextScrollSelectorIndex = mMinValue; 1618 } 1619 selectorIndices[selectorIndices.length - 1] = nextScrollSelectorIndex; 1620 ensureCachedScrollSelectorValue(nextScrollSelectorIndex); 1621 } 1622 1623 /** 1624 * Decrements the <code>selectorIndices</code> whose string representations 1625 * will be displayed in the selector. 1626 */ 1627 private void decrementSelectorIndices(int[] selectorIndices) { 1628 for (int i = selectorIndices.length - 1; i > 0; i--) { 1629 selectorIndices[i] = selectorIndices[i - 1]; 1630 } 1631 int nextScrollSelectorIndex = selectorIndices[1] - 1; 1632 if (mWrapSelectorWheel && nextScrollSelectorIndex < mMinValue) { 1633 nextScrollSelectorIndex = mMaxValue; 1634 } 1635 selectorIndices[0] = nextScrollSelectorIndex; 1636 ensureCachedScrollSelectorValue(nextScrollSelectorIndex); 1637 } 1638 1639 /** 1640 * Ensures we have a cached string representation of the given <code> 1641 * selectorIndex</code> to avoid multiple instantiations of the same string. 1642 */ 1643 private void ensureCachedScrollSelectorValue(int selectorIndex) { 1644 SparseArray<String> cache = mSelectorIndexToStringCache; 1645 String scrollSelectorValue = cache.get(selectorIndex); 1646 if (scrollSelectorValue != null) { 1647 return; 1648 } 1649 if (selectorIndex < mMinValue || selectorIndex > mMaxValue) { 1650 scrollSelectorValue = ""; 1651 } else { 1652 if (mDisplayedValues != null) { 1653 int displayedValueIndex = selectorIndex - mMinValue; 1654 scrollSelectorValue = mDisplayedValues[displayedValueIndex]; 1655 } else { 1656 scrollSelectorValue = formatNumber(selectorIndex); 1657 } 1658 } 1659 cache.put(selectorIndex, scrollSelectorValue); 1660 } 1661 1662 private String formatNumber(int value) { 1663 return (mFormatter != null) ? mFormatter.format(value) : String.valueOf(value); 1664 } 1665 1666 private void validateInputTextView(View v) { 1667 String str = String.valueOf(((TextView) v).getText()); 1668 if (TextUtils.isEmpty(str)) { 1669 // Restore to the old value as we don't allow empty values 1670 updateInputTextView(); 1671 } else { 1672 // Check the new value and ensure it's in range 1673 int current = getSelectedPos(str.toString()); 1674 setValueInternal(current, true); 1675 } 1676 } 1677 1678 /** 1679 * Updates the view of this NumberPicker. If displayValues were specified in 1680 * the string corresponding to the index specified by the current value will 1681 * be returned. Otherwise, the formatter specified in {@link #setFormatter} 1682 * will be used to format the number. 1683 * 1684 * @return Whether the text was updated. 1685 */ 1686 private boolean updateInputTextView() { 1687 /* 1688 * If we don't have displayed values then use the current number else 1689 * find the correct value in the displayed values for the current 1690 * number. 1691 */ 1692 String text = (mDisplayedValues == null) ? formatNumber(mValue) 1693 : mDisplayedValues[mValue - mMinValue]; 1694 if (!TextUtils.isEmpty(text) && !text.equals(mInputText.getText().toString())) { 1695 mInputText.setText(text); 1696 return true; 1697 } 1698 1699 return false; 1700 } 1701 1702 /** 1703 * Notifies the listener, if registered, of a change of the value of this 1704 * NumberPicker. 1705 */ 1706 private void notifyChange(int previous, int current) { 1707 if (mOnValueChangeListener != null) { 1708 mOnValueChangeListener.onValueChange(this, previous, mValue); 1709 } 1710 } 1711 1712 /** 1713 * Posts a command for changing the current value by one. 1714 * 1715 * @param increment Whether to increment or decrement the value. 1716 */ 1717 private void postChangeCurrentByOneFromLongPress(boolean increment, long delayMillis) { 1718 if (mChangeCurrentByOneFromLongPressCommand == null) { 1719 mChangeCurrentByOneFromLongPressCommand = new ChangeCurrentByOneFromLongPressCommand(); 1720 } else { 1721 removeCallbacks(mChangeCurrentByOneFromLongPressCommand); 1722 } 1723 mChangeCurrentByOneFromLongPressCommand.setStep(increment); 1724 postDelayed(mChangeCurrentByOneFromLongPressCommand, delayMillis); 1725 } 1726 1727 /** 1728 * Removes the command for changing the current value by one. 1729 */ 1730 private void removeChangeCurrentByOneFromLongPress() { 1731 if (mChangeCurrentByOneFromLongPressCommand != null) { 1732 removeCallbacks(mChangeCurrentByOneFromLongPressCommand); 1733 } 1734 } 1735 1736 /** 1737 * Posts a command for beginning an edit of the current value via IME on 1738 * long press. 1739 */ 1740 private void postBeginSoftInputOnLongPressCommand() { 1741 if (mBeginSoftInputOnLongPressCommand == null) { 1742 mBeginSoftInputOnLongPressCommand = new BeginSoftInputOnLongPressCommand(); 1743 } else { 1744 removeCallbacks(mBeginSoftInputOnLongPressCommand); 1745 } 1746 postDelayed(mBeginSoftInputOnLongPressCommand, ViewConfiguration.getLongPressTimeout()); 1747 } 1748 1749 /** 1750 * Removes the command for beginning an edit of the current value via IME. 1751 */ 1752 private void removeBeginSoftInputCommand() { 1753 if (mBeginSoftInputOnLongPressCommand != null) { 1754 removeCallbacks(mBeginSoftInputOnLongPressCommand); 1755 } 1756 } 1757 1758 /** 1759 * Removes all pending callback from the message queue. 1760 */ 1761 private void removeAllCallbacks() { 1762 if (mChangeCurrentByOneFromLongPressCommand != null) { 1763 removeCallbacks(mChangeCurrentByOneFromLongPressCommand); 1764 } 1765 if (mSetSelectionCommand != null) { 1766 removeCallbacks(mSetSelectionCommand); 1767 } 1768 if (mBeginSoftInputOnLongPressCommand != null) { 1769 removeCallbacks(mBeginSoftInputOnLongPressCommand); 1770 } 1771 } 1772 1773 /** 1774 * @return The selected index given its displayed <code>value</code>. 1775 */ 1776 private int getSelectedPos(String value) { 1777 if (mDisplayedValues == null) { 1778 try { 1779 return Integer.parseInt(value); 1780 } catch (NumberFormatException e) { 1781 // Ignore as if it's not a number we don't care 1782 } 1783 } else { 1784 for (int i = 0; i < mDisplayedValues.length; i++) { 1785 // Don't force the user to type in jan when ja will do 1786 value = value.toLowerCase(); 1787 if (mDisplayedValues[i].toLowerCase().startsWith(value)) { 1788 return mMinValue + i; 1789 } 1790 } 1791 1792 /* 1793 * The user might have typed in a number into the month field i.e. 1794 * 10 instead of OCT so support that too. 1795 */ 1796 try { 1797 return Integer.parseInt(value); 1798 } catch (NumberFormatException e) { 1799 1800 // Ignore as if it's not a number we don't care 1801 } 1802 } 1803 return mMinValue; 1804 } 1805 1806 /** 1807 * Posts an {@link SetSelectionCommand} from the given <code>selectionStart 1808 * </code> to <code>selectionEnd</code>. 1809 */ 1810 private void postSetSelectionCommand(int selectionStart, int selectionEnd) { 1811 if (mSetSelectionCommand == null) { 1812 mSetSelectionCommand = new SetSelectionCommand(); 1813 } else { 1814 removeCallbacks(mSetSelectionCommand); 1815 } 1816 mSetSelectionCommand.mSelectionStart = selectionStart; 1817 mSetSelectionCommand.mSelectionEnd = selectionEnd; 1818 post(mSetSelectionCommand); 1819 } 1820 1821 /** 1822 * Filter for accepting only valid indices or prefixes of the string 1823 * representation of valid indices. 1824 */ 1825 class InputTextFilter extends NumberKeyListener { 1826 1827 // XXX This doesn't allow for range limits when controlled by a 1828 // soft input method! 1829 public int getInputType() { 1830 return InputType.TYPE_CLASS_TEXT; 1831 } 1832 1833 @Override 1834 protected char[] getAcceptedChars() { 1835 return DIGIT_CHARACTERS; 1836 } 1837 1838 @Override 1839 public CharSequence filter( 1840 CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 1841 if (mDisplayedValues == null) { 1842 CharSequence filtered = super.filter(source, start, end, dest, dstart, dend); 1843 if (filtered == null) { 1844 filtered = source.subSequence(start, end); 1845 } 1846 1847 String result = String.valueOf(dest.subSequence(0, dstart)) + filtered 1848 + dest.subSequence(dend, dest.length()); 1849 1850 if ("".equals(result)) { 1851 return result; 1852 } 1853 int val = getSelectedPos(result); 1854 1855 /* 1856 * Ensure the user can't type in a value greater than the max 1857 * allowed. We have to allow less than min as the user might 1858 * want to delete some numbers and then type a new number. 1859 */ 1860 if (val > mMaxValue) { 1861 return ""; 1862 } else { 1863 return filtered; 1864 } 1865 } else { 1866 CharSequence filtered = String.valueOf(source.subSequence(start, end)); 1867 if (TextUtils.isEmpty(filtered)) { 1868 return ""; 1869 } 1870 String result = String.valueOf(dest.subSequence(0, dstart)) + filtered 1871 + dest.subSequence(dend, dest.length()); 1872 String str = String.valueOf(result).toLowerCase(); 1873 for (String val : mDisplayedValues) { 1874 String valLowerCase = val.toLowerCase(); 1875 if (valLowerCase.startsWith(str)) { 1876 postSetSelectionCommand(result.length(), val.length()); 1877 return val.subSequence(dstart, val.length()); 1878 } 1879 } 1880 return ""; 1881 } 1882 } 1883 } 1884 1885 /** 1886 * Ensures that the scroll wheel is adjusted i.e. there is no offset and the 1887 * middle element is in the middle of the widget. 1888 * 1889 * @return Whether an adjustment has been made. 1890 */ 1891 private boolean ensureScrollWheelAdjusted() { 1892 // adjust to the closest value 1893 int deltaY = mInitialScrollOffset - mCurrentScrollOffset; 1894 if (deltaY != 0) { 1895 mPreviousScrollerY = 0; 1896 if (Math.abs(deltaY) > mSelectorElementHeight / 2) { 1897 deltaY += (deltaY > 0) ? -mSelectorElementHeight : mSelectorElementHeight; 1898 } 1899 mAdjustScroller.startScroll(0, 0, 0, deltaY, SELECTOR_ADJUSTMENT_DURATION_MILLIS); 1900 invalidate(); 1901 return true; 1902 } 1903 return false; 1904 } 1905 1906 private void snapToNextValue(boolean increment) { 1907 int deltaY = mCurrentScrollOffset - mInitialScrollOffset; 1908 int amountToScroll = 0; 1909 if (deltaY != 0) { 1910 mPreviousScrollerY = 0; 1911 if (deltaY > 0) { 1912 if (increment) { 1913 amountToScroll = - deltaY; 1914 } else { 1915 amountToScroll = mSelectorElementHeight - deltaY; 1916 } 1917 } else { 1918 if (increment) { 1919 amountToScroll = - mSelectorElementHeight - deltaY; 1920 } else { 1921 amountToScroll = - deltaY; 1922 } 1923 } 1924 mFlingScroller.startScroll(0, 0, 0, amountToScroll, SNAP_SCROLL_DURATION); 1925 invalidate(); 1926 } 1927 } 1928 1929 private void snapToClosestValue() { 1930 // adjust to the closest value 1931 int deltaY = mInitialScrollOffset - mCurrentScrollOffset; 1932 if (deltaY != 0) { 1933 mPreviousScrollerY = 0; 1934 if (Math.abs(deltaY) > mSelectorElementHeight / 2) { 1935 deltaY += (deltaY > 0) ? -mSelectorElementHeight : mSelectorElementHeight; 1936 } 1937 mFlingScroller.startScroll(0, 0, 0, deltaY, SNAP_SCROLL_DURATION); 1938 invalidate(); 1939 } 1940 } 1941 1942 /** 1943 * Command for setting the input text selection. 1944 */ 1945 class SetSelectionCommand implements Runnable { 1946 private int mSelectionStart; 1947 1948 private int mSelectionEnd; 1949 1950 public void run() { 1951 mInputText.setSelection(mSelectionStart, mSelectionEnd); 1952 } 1953 } 1954 1955 /** 1956 * Command for changing the current value from a long press by one. 1957 */ 1958 class ChangeCurrentByOneFromLongPressCommand implements Runnable { 1959 private boolean mIncrement; 1960 1961 private void setStep(boolean increment) { 1962 mIncrement = increment; 1963 } 1964 1965 @Override 1966 public void run() { 1967 changeValueByOne(mIncrement); 1968 postDelayed(this, mLongPressUpdateInterval); 1969 } 1970 } 1971 1972 /** 1973 * @hide 1974 */ 1975 public static class CustomEditText extends EditText { 1976 1977 public CustomEditText(Context context, AttributeSet attrs) { 1978 super(context, attrs); 1979 } 1980 1981 @Override 1982 public void onEditorAction(int actionCode) { 1983 super.onEditorAction(actionCode); 1984 if (actionCode == EditorInfo.IME_ACTION_DONE) { 1985 clearFocus(); 1986 } 1987 } 1988 } 1989 1990 /** 1991 * Command for beginning soft input on long press. 1992 */ 1993 class BeginSoftInputOnLongPressCommand implements Runnable { 1994 1995 @Override 1996 public void run() { 1997 showSoftInput(); 1998 mIngonreMoveEvents = true; 1999 } 2000 } 2001 2002 class AccessibilityNodeProviderImpl extends AccessibilityNodeProvider { 2003 private static final int VIRTUAL_VIEW_ID_INCREMENT = 1; 2004 2005 private static final int VIRTUAL_VIEW_ID_INPUT = 2; 2006 2007 private static final int VIRTUAL_VIEW_ID_DECREMENT = 3; 2008 2009 private final Rect mTempRect = new Rect(); 2010 2011 private final int[] mTempArray = new int[2]; 2012 2013 @Override 2014 public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) { 2015 switch (virtualViewId) { 2016 case View.NO_ID: 2017 return createAccessibilityNodeInfoForNumberPicker( mScrollX, mScrollY, 2018 mScrollX + (mRight - mLeft), mScrollY + (mBottom - mTop)); 2019 case VIRTUAL_VIEW_ID_DECREMENT: 2020 return createAccessibilityNodeInfoForVirtualButton(VIRTUAL_VIEW_ID_DECREMENT, 2021 getVirtualDecrementButtonText(), mScrollX, mScrollY, 2022 mScrollX + (mRight - mLeft), 2023 mTopSelectionDividerTop + mSelectionDividerHeight); 2024 case VIRTUAL_VIEW_ID_INPUT: 2025 return createAccessibiltyNodeInfoForInputText(); 2026 case VIRTUAL_VIEW_ID_INCREMENT: 2027 return createAccessibilityNodeInfoForVirtualButton(VIRTUAL_VIEW_ID_INCREMENT, 2028 getVirtualIncrementButtonText(), mScrollX, 2029 mBottomSelectionDividerBottom - mSelectionDividerHeight, 2030 mScrollX + (mRight - mLeft), mScrollY + (mBottom - mTop)); 2031 } 2032 return super.createAccessibilityNodeInfo(virtualViewId); 2033 } 2034 2035 @Override 2036 public List<AccessibilityNodeInfo> findAccessibilityNodeInfosByText(String searched, 2037 int virtualViewId) { 2038 if (TextUtils.isEmpty(searched)) { 2039 return Collections.emptyList(); 2040 } 2041 String searchedLowerCase = searched.toLowerCase(); 2042 List<AccessibilityNodeInfo> result = new ArrayList<AccessibilityNodeInfo>(); 2043 switch (virtualViewId) { 2044 case View.NO_ID: { 2045 findAccessibilityNodeInfosByTextInChild(searchedLowerCase, 2046 VIRTUAL_VIEW_ID_DECREMENT, result); 2047 findAccessibilityNodeInfosByTextInChild(searchedLowerCase, 2048 VIRTUAL_VIEW_ID_INPUT, result); 2049 findAccessibilityNodeInfosByTextInChild(searchedLowerCase, 2050 VIRTUAL_VIEW_ID_INCREMENT, result); 2051 return result; 2052 } 2053 case VIRTUAL_VIEW_ID_DECREMENT: 2054 case VIRTUAL_VIEW_ID_INCREMENT: 2055 case VIRTUAL_VIEW_ID_INPUT: { 2056 findAccessibilityNodeInfosByTextInChild(searchedLowerCase, virtualViewId, 2057 result); 2058 return result; 2059 } 2060 } 2061 return super.findAccessibilityNodeInfosByText(searched, virtualViewId); 2062 } 2063 2064 @Override 2065 public boolean performAccessibilityAction(int action, int virtualViewId) { 2066 switch (virtualViewId) { 2067 case VIRTUAL_VIEW_ID_INPUT: { 2068 switch (action) { 2069 case AccessibilityNodeInfo.ACTION_FOCUS: { 2070 if (!mInputText.isFocused()) { 2071 return mInputText.requestFocus(); 2072 } 2073 } break; 2074 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 2075 if (mInputText.isFocused()) { 2076 mInputText.clearFocus(); 2077 return true; 2078 } 2079 } break; 2080 } 2081 } break; 2082 } 2083 return super.performAccessibilityAction(action, virtualViewId); 2084 } 2085 2086 public void sendAccessibilityEventForVirtualView(int virtualViewId, int eventType) { 2087 switch (virtualViewId) { 2088 case VIRTUAL_VIEW_ID_DECREMENT: { 2089 sendAccessibilityEventForVirtualButton(virtualViewId, eventType, 2090 getVirtualDecrementButtonText()); 2091 } break; 2092 case VIRTUAL_VIEW_ID_INPUT: { 2093 sendAccessibilityEventForVirtualText(eventType); 2094 } break; 2095 case VIRTUAL_VIEW_ID_INCREMENT: { 2096 sendAccessibilityEventForVirtualButton(virtualViewId, eventType, 2097 getVirtualIncrementButtonText()); 2098 } break; 2099 } 2100 } 2101 2102 private void sendAccessibilityEventForVirtualText(int eventType) { 2103 AccessibilityEvent event = AccessibilityEvent.obtain(eventType); 2104 mInputText.onInitializeAccessibilityEvent(event); 2105 mInputText.onPopulateAccessibilityEvent(event); 2106 event.setSource(NumberPicker.this, VIRTUAL_VIEW_ID_INPUT); 2107 requestSendAccessibilityEvent(NumberPicker.this, event); 2108 } 2109 2110 private void sendAccessibilityEventForVirtualButton(int virtualViewId, int eventType, 2111 String text) { 2112 AccessibilityEvent event = AccessibilityEvent.obtain(eventType); 2113 event.setClassName(Button.class.getName()); 2114 event.setPackageName(mContext.getPackageName()); 2115 event.getText().add(text); 2116 event.setEnabled(NumberPicker.this.isEnabled()); 2117 event.setSource(NumberPicker.this, virtualViewId); 2118 requestSendAccessibilityEvent(NumberPicker.this, event); 2119 } 2120 2121 private void findAccessibilityNodeInfosByTextInChild(String searchedLowerCase, 2122 int virtualViewId, List<AccessibilityNodeInfo> outResult) { 2123 switch (virtualViewId) { 2124 case VIRTUAL_VIEW_ID_DECREMENT: { 2125 String text = getVirtualDecrementButtonText(); 2126 if (!TextUtils.isEmpty(text) 2127 && text.toString().toLowerCase().contains(searchedLowerCase)) { 2128 outResult.add(createAccessibilityNodeInfo(VIRTUAL_VIEW_ID_DECREMENT)); 2129 } 2130 } return; 2131 case VIRTUAL_VIEW_ID_INPUT: { 2132 CharSequence text = mInputText.getText(); 2133 if (!TextUtils.isEmpty(text) && 2134 text.toString().toLowerCase().contains(searchedLowerCase)) { 2135 outResult.add(createAccessibilityNodeInfo(VIRTUAL_VIEW_ID_INPUT)); 2136 return; 2137 } 2138 CharSequence contentDesc = mInputText.getText(); 2139 if (!TextUtils.isEmpty(contentDesc) && 2140 contentDesc.toString().toLowerCase().contains(searchedLowerCase)) { 2141 outResult.add(createAccessibilityNodeInfo(VIRTUAL_VIEW_ID_INPUT)); 2142 return; 2143 } 2144 } break; 2145 case VIRTUAL_VIEW_ID_INCREMENT: { 2146 String text = getVirtualIncrementButtonText(); 2147 if (!TextUtils.isEmpty(text) 2148 && text.toString().toLowerCase().contains(searchedLowerCase)) { 2149 outResult.add(createAccessibilityNodeInfo(VIRTUAL_VIEW_ID_INCREMENT)); 2150 } 2151 } return; 2152 } 2153 } 2154 2155 private AccessibilityNodeInfo createAccessibiltyNodeInfoForInputText() { 2156 AccessibilityNodeInfo info = mInputText.createAccessibilityNodeInfo(); 2157 info.setLongClickable(true); 2158 info.setSource(NumberPicker.this, VIRTUAL_VIEW_ID_INPUT); 2159 return info; 2160 } 2161 2162 private AccessibilityNodeInfo createAccessibilityNodeInfoForVirtualButton(int virtualViewId, 2163 String text, int left, int top, int right, int bottom) { 2164 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(); 2165 info.setClassName(Button.class.getName()); 2166 info.setPackageName(mContext.getPackageName()); 2167 info.setSource(NumberPicker.this, virtualViewId); 2168 info.setParent(NumberPicker.this); 2169 info.addChild(NumberPicker.this, VIRTUAL_VIEW_ID_DECREMENT); 2170 info.addChild(NumberPicker.this, VIRTUAL_VIEW_ID_INPUT); 2171 info.addChild(NumberPicker.this, VIRTUAL_VIEW_ID_INCREMENT); 2172 info.setText(text); 2173 info.setClickable(true); 2174 info.setLongClickable(true); 2175 info.setEnabled(NumberPicker.this.isEnabled()); 2176 Rect boundsInParent = mTempRect; 2177 boundsInParent.set(left, top, right, bottom); 2178 info.setBoundsInParent(boundsInParent); 2179 Rect boundsInScreen = boundsInParent; 2180 int[] locationOnScreen = mTempArray; 2181 getLocationOnScreen(locationOnScreen); 2182 boundsInScreen.offsetTo(0, 0); 2183 boundsInScreen.offset(locationOnScreen[0], locationOnScreen[1]); 2184 info.setBoundsInScreen(boundsInScreen); 2185 return info; 2186 } 2187 2188 private AccessibilityNodeInfo createAccessibilityNodeInfoForNumberPicker(int left, int top, 2189 int right, int bottom) { 2190 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(); 2191 info.setClassName(Button.class.getName()); 2192 info.setPackageName(mContext.getPackageName()); 2193 info.setSource(NumberPicker.this); 2194 info.setParent((View) getParent()); 2195 info.setEnabled(NumberPicker.this.isEnabled()); 2196 info.setScrollable(true); 2197 Rect boundsInParent = mTempRect; 2198 boundsInParent.set(left, top, right, bottom); 2199 info.setBoundsInParent(boundsInParent); 2200 Rect boundsInScreen = boundsInParent; 2201 int[] locationOnScreen = mTempArray; 2202 getLocationOnScreen(locationOnScreen); 2203 boundsInScreen.offsetTo(0, 0); 2204 boundsInScreen.offset(locationOnScreen[0], locationOnScreen[1]); 2205 info.setBoundsInScreen(boundsInScreen); 2206 return info; 2207 } 2208 2209 private String getVirtualDecrementButtonText() { 2210 int value = mValue - 1; 2211 if (mWrapSelectorWheel) { 2212 value = getWrappedSelectorIndex(value); 2213 } 2214 if (value >= mMinValue) { 2215 return (mDisplayedValues == null) ? formatNumber(value) 2216 : mDisplayedValues[value - mMinValue]; 2217 } 2218 return null; 2219 } 2220 2221 private String getVirtualIncrementButtonText() { 2222 int value = mValue + 1; 2223 if (mWrapSelectorWheel) { 2224 value = getWrappedSelectorIndex(value); 2225 } 2226 if (value <= mMaxValue) { 2227 return (mDisplayedValues == null) ? formatNumber(value) 2228 : mDisplayedValues[value - mMinValue]; 2229 } 2230 return null; 2231 } 2232 } 2233} 2234