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