NumberPicker.java revision 5132d62600484bb4fce86295b288c782bee91de8
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 inclusive. 1318 * 1319 * <strong>Note:</strong> The length of the displayed values array 1320 * set via {@link #setDisplayedValues(String[])} must be equal to the 1321 * range of selectable numbers which is equal to 1322 * {@link #getMaxValue()} - {@link #getMinValue()} + 1. 1323 */ 1324 public void setMinValue(int minValue) { 1325 if (mMinValue == minValue) { 1326 return; 1327 } 1328 if (minValue < 0) { 1329 throw new IllegalArgumentException("minValue must be >= 0"); 1330 } 1331 mMinValue = minValue; 1332 if (mMinValue > mValue) { 1333 mValue = mMinValue; 1334 } 1335 boolean wrapSelectorWheel = mMaxValue - mMinValue > mSelectorIndices.length; 1336 setWrapSelectorWheel(wrapSelectorWheel); 1337 initializeSelectorWheelIndices(); 1338 updateInputTextView(); 1339 tryComputeMaxWidth(); 1340 invalidate(); 1341 } 1342 1343 /** 1344 * Returns the max value of the picker. 1345 * 1346 * @return The max value. 1347 */ 1348 public int getMaxValue() { 1349 return mMaxValue; 1350 } 1351 1352 /** 1353 * Sets the max value of the picker. 1354 * 1355 * @param maxValue The max value inclusive. 1356 * 1357 * <strong>Note:</strong> The length of the displayed values array 1358 * set via {@link #setDisplayedValues(String[])} must be equal to the 1359 * range of selectable numbers which is equal to 1360 * {@link #getMaxValue()} - {@link #getMinValue()} + 1. 1361 */ 1362 public void setMaxValue(int maxValue) { 1363 if (mMaxValue == maxValue) { 1364 return; 1365 } 1366 if (maxValue < 0) { 1367 throw new IllegalArgumentException("maxValue must be >= 0"); 1368 } 1369 mMaxValue = maxValue; 1370 if (mMaxValue < mValue) { 1371 mValue = mMaxValue; 1372 } 1373 boolean wrapSelectorWheel = mMaxValue - mMinValue > mSelectorIndices.length; 1374 setWrapSelectorWheel(wrapSelectorWheel); 1375 initializeSelectorWheelIndices(); 1376 updateInputTextView(); 1377 tryComputeMaxWidth(); 1378 invalidate(); 1379 } 1380 1381 /** 1382 * Gets the values to be displayed instead of string values. 1383 * 1384 * @return The displayed values. 1385 */ 1386 public String[] getDisplayedValues() { 1387 return mDisplayedValues; 1388 } 1389 1390 /** 1391 * Sets the values to be displayed. 1392 * 1393 * @param displayedValues The displayed values. 1394 * 1395 * <strong>Note:</strong> The length of the displayed values array 1396 * must be equal to the range of selectable numbers which is equal to 1397 * {@link #getMaxValue()} - {@link #getMinValue()} + 1. 1398 */ 1399 public void setDisplayedValues(String[] displayedValues) { 1400 if (mDisplayedValues == displayedValues) { 1401 return; 1402 } 1403 mDisplayedValues = displayedValues; 1404 if (mDisplayedValues != null) { 1405 // Allow text entry rather than strictly numeric entry. 1406 mInputText.setRawInputType(InputType.TYPE_CLASS_TEXT 1407 | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); 1408 } else { 1409 mInputText.setRawInputType(InputType.TYPE_CLASS_NUMBER); 1410 } 1411 updateInputTextView(); 1412 initializeSelectorWheelIndices(); 1413 tryComputeMaxWidth(); 1414 } 1415 1416 @Override 1417 protected float getTopFadingEdgeStrength() { 1418 return TOP_AND_BOTTOM_FADING_EDGE_STRENGTH; 1419 } 1420 1421 @Override 1422 protected float getBottomFadingEdgeStrength() { 1423 return TOP_AND_BOTTOM_FADING_EDGE_STRENGTH; 1424 } 1425 1426 @Override 1427 protected void onDetachedFromWindow() { 1428 removeAllCallbacks(); 1429 } 1430 1431 @Override 1432 protected void onDraw(Canvas canvas) { 1433 if (!mHasSelectorWheel) { 1434 super.onDraw(canvas); 1435 return; 1436 } 1437 float x = (mRight - mLeft) / 2; 1438 float y = mCurrentScrollOffset; 1439 1440 // draw the virtual buttons pressed state if needed 1441 if (mVirtualButtonPressedDrawable != null 1442 && mScrollState == OnScrollListener.SCROLL_STATE_IDLE) { 1443 if (mDecrementVirtualButtonPressed) { 1444 mVirtualButtonPressedDrawable.setState(PRESSED_STATE_SET); 1445 mVirtualButtonPressedDrawable.setBounds(0, 0, mRight, mTopSelectionDividerTop); 1446 mVirtualButtonPressedDrawable.draw(canvas); 1447 } 1448 if (mIncrementVirtualButtonPressed) { 1449 mVirtualButtonPressedDrawable.setState(PRESSED_STATE_SET); 1450 mVirtualButtonPressedDrawable.setBounds(0, mBottomSelectionDividerBottom, mRight, 1451 mBottom); 1452 mVirtualButtonPressedDrawable.draw(canvas); 1453 } 1454 } 1455 1456 // draw the selector wheel 1457 int[] selectorIndices = mSelectorIndices; 1458 for (int i = 0; i < selectorIndices.length; i++) { 1459 int selectorIndex = selectorIndices[i]; 1460 String scrollSelectorValue = mSelectorIndexToStringCache.get(selectorIndex); 1461 // Do not draw the middle item if input is visible since the input 1462 // is shown only if the wheel is static and it covers the middle 1463 // item. Otherwise, if the user starts editing the text via the 1464 // IME he may see a dimmed version of the old value intermixed 1465 // with the new one. 1466 if (i != SELECTOR_MIDDLE_ITEM_INDEX || mInputText.getVisibility() != VISIBLE) { 1467 canvas.drawText(scrollSelectorValue, x, y, mSelectorWheelPaint); 1468 } 1469 y += mSelectorElementHeight; 1470 } 1471 1472 // draw the selection dividers 1473 if (mSelectionDivider != null) { 1474 // draw the top divider 1475 int topOfTopDivider = mTopSelectionDividerTop; 1476 int bottomOfTopDivider = topOfTopDivider + mSelectionDividerHeight; 1477 mSelectionDivider.setBounds(0, topOfTopDivider, mRight, bottomOfTopDivider); 1478 mSelectionDivider.draw(canvas); 1479 1480 // draw the bottom divider 1481 int bottomOfBottomDivider = mBottomSelectionDividerBottom; 1482 int topOfBottomDivider = bottomOfBottomDivider - mSelectionDividerHeight; 1483 mSelectionDivider.setBounds(0, topOfBottomDivider, mRight, bottomOfBottomDivider); 1484 mSelectionDivider.draw(canvas); 1485 } 1486 } 1487 1488 @Override 1489 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 1490 super.onInitializeAccessibilityEvent(event); 1491 event.setClassName(NumberPicker.class.getName()); 1492 event.setScrollable(true); 1493 event.setScrollY((mMinValue + mValue) * mSelectorElementHeight); 1494 event.setMaxScrollY((mMaxValue - mMinValue) * mSelectorElementHeight); 1495 } 1496 1497 @Override 1498 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 1499 if (!mHasSelectorWheel) { 1500 return super.getAccessibilityNodeProvider(); 1501 } 1502 if (mAccessibilityNodeProvider == null) { 1503 mAccessibilityNodeProvider = new AccessibilityNodeProviderImpl(); 1504 } 1505 return mAccessibilityNodeProvider; 1506 } 1507 1508 /** 1509 * Makes a measure spec that tries greedily to use the max value. 1510 * 1511 * @param measureSpec The measure spec. 1512 * @param maxSize The max value for the size. 1513 * @return A measure spec greedily imposing the max size. 1514 */ 1515 private int makeMeasureSpec(int measureSpec, int maxSize) { 1516 if (maxSize == SIZE_UNSPECIFIED) { 1517 return measureSpec; 1518 } 1519 final int size = MeasureSpec.getSize(measureSpec); 1520 final int mode = MeasureSpec.getMode(measureSpec); 1521 switch (mode) { 1522 case MeasureSpec.EXACTLY: 1523 return measureSpec; 1524 case MeasureSpec.AT_MOST: 1525 return MeasureSpec.makeMeasureSpec(Math.min(size, maxSize), MeasureSpec.EXACTLY); 1526 case MeasureSpec.UNSPECIFIED: 1527 return MeasureSpec.makeMeasureSpec(maxSize, MeasureSpec.EXACTLY); 1528 default: 1529 throw new IllegalArgumentException("Unknown measure mode: " + mode); 1530 } 1531 } 1532 1533 /** 1534 * Utility to reconcile a desired size and state, with constraints imposed 1535 * by a MeasureSpec. Tries to respect the min size, unless a different size 1536 * is imposed by the constraints. 1537 * 1538 * @param minSize The minimal desired size. 1539 * @param measuredSize The currently measured size. 1540 * @param measureSpec The current measure spec. 1541 * @return The resolved size and state. 1542 */ 1543 private int resolveSizeAndStateRespectingMinSize( 1544 int minSize, int measuredSize, int measureSpec) { 1545 if (minSize != SIZE_UNSPECIFIED) { 1546 final int desiredWidth = Math.max(minSize, measuredSize); 1547 return resolveSizeAndState(desiredWidth, measureSpec, 0); 1548 } else { 1549 return measuredSize; 1550 } 1551 } 1552 1553 /** 1554 * Resets the selector indices and clear the cached string representation of 1555 * these indices. 1556 */ 1557 private void initializeSelectorWheelIndices() { 1558 mSelectorIndexToStringCache.clear(); 1559 int[] selectorIndices = mSelectorIndices; 1560 int current = getValue(); 1561 for (int i = 0; i < mSelectorIndices.length; i++) { 1562 int selectorIndex = current + (i - SELECTOR_MIDDLE_ITEM_INDEX); 1563 if (mWrapSelectorWheel) { 1564 selectorIndex = getWrappedSelectorIndex(selectorIndex); 1565 } 1566 selectorIndices[i] = selectorIndex; 1567 ensureCachedScrollSelectorValue(selectorIndices[i]); 1568 } 1569 } 1570 1571 /** 1572 * Sets the current value of this NumberPicker. 1573 * 1574 * @param current The new value of the NumberPicker. 1575 * @param notifyChange Whether to notify if the current value changed. 1576 */ 1577 private void setValueInternal(int current, boolean notifyChange) { 1578 if (mValue == current) { 1579 return; 1580 } 1581 // Wrap around the values if we go past the start or end 1582 if (mWrapSelectorWheel) { 1583 current = getWrappedSelectorIndex(current); 1584 } else { 1585 current = Math.max(current, mMinValue); 1586 current = Math.min(current, mMaxValue); 1587 } 1588 int previous = mValue; 1589 mValue = current; 1590 updateInputTextView(); 1591 if (notifyChange) { 1592 notifyChange(previous, current); 1593 } 1594 initializeSelectorWheelIndices(); 1595 invalidate(); 1596 } 1597 1598 /** 1599 * Changes the current value by one which is increment or 1600 * decrement based on the passes argument. 1601 * decrement the current value. 1602 * 1603 * @param increment True to increment, false to decrement. 1604 */ 1605 private void changeValueByOne(boolean increment) { 1606 if (mHasSelectorWheel) { 1607 mInputText.setVisibility(View.INVISIBLE); 1608 if (!moveToFinalScrollerPosition(mFlingScroller)) { 1609 moveToFinalScrollerPosition(mAdjustScroller); 1610 } 1611 mPreviousScrollerY = 0; 1612 if (increment) { 1613 mFlingScroller.startScroll(0, 0, 0, -mSelectorElementHeight, SNAP_SCROLL_DURATION); 1614 } else { 1615 mFlingScroller.startScroll(0, 0, 0, mSelectorElementHeight, SNAP_SCROLL_DURATION); 1616 } 1617 invalidate(); 1618 } else { 1619 if (increment) { 1620 setValueInternal(mValue + 1, true); 1621 } else { 1622 setValueInternal(mValue - 1, true); 1623 } 1624 } 1625 } 1626 1627 private void initializeSelectorWheel() { 1628 initializeSelectorWheelIndices(); 1629 int[] selectorIndices = mSelectorIndices; 1630 int totalTextHeight = selectorIndices.length * mTextSize; 1631 float totalTextGapHeight = (mBottom - mTop) - totalTextHeight; 1632 float textGapCount = selectorIndices.length; 1633 mSelectorTextGapHeight = (int) (totalTextGapHeight / textGapCount + 0.5f); 1634 mSelectorElementHeight = mTextSize + mSelectorTextGapHeight; 1635 // Ensure that the middle item is positioned the same as the text in 1636 // mInputText 1637 int editTextTextPosition = mInputText.getBaseline() + mInputText.getTop(); 1638 mInitialScrollOffset = editTextTextPosition 1639 - (mSelectorElementHeight * SELECTOR_MIDDLE_ITEM_INDEX); 1640 mCurrentScrollOffset = mInitialScrollOffset; 1641 updateInputTextView(); 1642 } 1643 1644 private void initializeFadingEdges() { 1645 setVerticalFadingEdgeEnabled(true); 1646 setFadingEdgeLength((mBottom - mTop - mTextSize) / 2); 1647 } 1648 1649 /** 1650 * Callback invoked upon completion of a given <code>scroller</code>. 1651 */ 1652 private void onScrollerFinished(Scroller scroller) { 1653 if (scroller == mFlingScroller) { 1654 if (!ensureScrollWheelAdjusted()) { 1655 updateInputTextView(); 1656 } 1657 onScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); 1658 } else { 1659 if (mScrollState != OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { 1660 updateInputTextView(); 1661 } 1662 } 1663 } 1664 1665 /** 1666 * Handles transition to a given <code>scrollState</code> 1667 */ 1668 private void onScrollStateChange(int scrollState) { 1669 if (mScrollState == scrollState) { 1670 return; 1671 } 1672 mScrollState = scrollState; 1673 if (mOnScrollListener != null) { 1674 mOnScrollListener.onScrollStateChange(this, scrollState); 1675 } 1676 } 1677 1678 /** 1679 * Flings the selector with the given <code>velocityY</code>. 1680 */ 1681 private void fling(int velocityY) { 1682 mPreviousScrollerY = 0; 1683 1684 if (velocityY > 0) { 1685 mFlingScroller.fling(0, 0, 0, velocityY, 0, 0, 0, Integer.MAX_VALUE); 1686 } else { 1687 mFlingScroller.fling(0, Integer.MAX_VALUE, 0, velocityY, 0, 0, 0, Integer.MAX_VALUE); 1688 } 1689 1690 invalidate(); 1691 } 1692 1693 /** 1694 * @return The wrapped index <code>selectorIndex</code> value. 1695 */ 1696 private int getWrappedSelectorIndex(int selectorIndex) { 1697 if (selectorIndex > mMaxValue) { 1698 return mMinValue + (selectorIndex - mMaxValue) % (mMaxValue - mMinValue) - 1; 1699 } else if (selectorIndex < mMinValue) { 1700 return mMaxValue - (mMinValue - selectorIndex) % (mMaxValue - mMinValue) + 1; 1701 } 1702 return selectorIndex; 1703 } 1704 1705 /** 1706 * Increments the <code>selectorIndices</code> whose string representations 1707 * will be displayed in the selector. 1708 */ 1709 private void incrementSelectorIndices(int[] selectorIndices) { 1710 for (int i = 0; i < selectorIndices.length - 1; i++) { 1711 selectorIndices[i] = selectorIndices[i + 1]; 1712 } 1713 int nextScrollSelectorIndex = selectorIndices[selectorIndices.length - 2] + 1; 1714 if (mWrapSelectorWheel && nextScrollSelectorIndex > mMaxValue) { 1715 nextScrollSelectorIndex = mMinValue; 1716 } 1717 selectorIndices[selectorIndices.length - 1] = nextScrollSelectorIndex; 1718 ensureCachedScrollSelectorValue(nextScrollSelectorIndex); 1719 } 1720 1721 /** 1722 * Decrements the <code>selectorIndices</code> whose string representations 1723 * will be displayed in the selector. 1724 */ 1725 private void decrementSelectorIndices(int[] selectorIndices) { 1726 for (int i = selectorIndices.length - 1; i > 0; i--) { 1727 selectorIndices[i] = selectorIndices[i - 1]; 1728 } 1729 int nextScrollSelectorIndex = selectorIndices[1] - 1; 1730 if (mWrapSelectorWheel && nextScrollSelectorIndex < mMinValue) { 1731 nextScrollSelectorIndex = mMaxValue; 1732 } 1733 selectorIndices[0] = nextScrollSelectorIndex; 1734 ensureCachedScrollSelectorValue(nextScrollSelectorIndex); 1735 } 1736 1737 /** 1738 * Ensures we have a cached string representation of the given <code> 1739 * selectorIndex</code> to avoid multiple instantiations of the same string. 1740 */ 1741 private void ensureCachedScrollSelectorValue(int selectorIndex) { 1742 SparseArray<String> cache = mSelectorIndexToStringCache; 1743 String scrollSelectorValue = cache.get(selectorIndex); 1744 if (scrollSelectorValue != null) { 1745 return; 1746 } 1747 if (selectorIndex < mMinValue || selectorIndex > mMaxValue) { 1748 scrollSelectorValue = ""; 1749 } else { 1750 if (mDisplayedValues != null) { 1751 int displayedValueIndex = selectorIndex - mMinValue; 1752 scrollSelectorValue = mDisplayedValues[displayedValueIndex]; 1753 } else { 1754 scrollSelectorValue = formatNumber(selectorIndex); 1755 } 1756 } 1757 cache.put(selectorIndex, scrollSelectorValue); 1758 } 1759 1760 private String formatNumber(int value) { 1761 return (mFormatter != null) ? mFormatter.format(value) : formatNumberWithLocale(value); 1762 } 1763 1764 private void validateInputTextView(View v) { 1765 String str = String.valueOf(((TextView) v).getText()); 1766 if (TextUtils.isEmpty(str)) { 1767 // Restore to the old value as we don't allow empty values 1768 updateInputTextView(); 1769 } else { 1770 // Check the new value and ensure it's in range 1771 int current = getSelectedPos(str.toString()); 1772 setValueInternal(current, true); 1773 } 1774 } 1775 1776 /** 1777 * Updates the view of this NumberPicker. If displayValues were specified in 1778 * the string corresponding to the index specified by the current value will 1779 * be returned. Otherwise, the formatter specified in {@link #setFormatter} 1780 * will be used to format the number. 1781 * 1782 * @return Whether the text was updated. 1783 */ 1784 private boolean updateInputTextView() { 1785 /* 1786 * If we don't have displayed values then use the current number else 1787 * find the correct value in the displayed values for the current 1788 * number. 1789 */ 1790 String text = (mDisplayedValues == null) ? formatNumber(mValue) 1791 : mDisplayedValues[mValue - mMinValue]; 1792 if (!TextUtils.isEmpty(text) && !text.equals(mInputText.getText().toString())) { 1793 mInputText.setText(text); 1794 return true; 1795 } 1796 1797 return false; 1798 } 1799 1800 /** 1801 * Notifies the listener, if registered, of a change of the value of this 1802 * NumberPicker. 1803 */ 1804 private void notifyChange(int previous, int current) { 1805 if (mOnValueChangeListener != null) { 1806 mOnValueChangeListener.onValueChange(this, previous, mValue); 1807 } 1808 } 1809 1810 /** 1811 * Posts a command for changing the current value by one. 1812 * 1813 * @param increment Whether to increment or decrement the value. 1814 */ 1815 private void postChangeCurrentByOneFromLongPress(boolean increment, long delayMillis) { 1816 if (mChangeCurrentByOneFromLongPressCommand == null) { 1817 mChangeCurrentByOneFromLongPressCommand = new ChangeCurrentByOneFromLongPressCommand(); 1818 } else { 1819 removeCallbacks(mChangeCurrentByOneFromLongPressCommand); 1820 } 1821 mChangeCurrentByOneFromLongPressCommand.setStep(increment); 1822 postDelayed(mChangeCurrentByOneFromLongPressCommand, delayMillis); 1823 } 1824 1825 /** 1826 * Removes the command for changing the current value by one. 1827 */ 1828 private void removeChangeCurrentByOneFromLongPress() { 1829 if (mChangeCurrentByOneFromLongPressCommand != null) { 1830 removeCallbacks(mChangeCurrentByOneFromLongPressCommand); 1831 } 1832 } 1833 1834 /** 1835 * Posts a command for beginning an edit of the current value via IME on 1836 * long press. 1837 */ 1838 private void postBeginSoftInputOnLongPressCommand() { 1839 if (mBeginSoftInputOnLongPressCommand == null) { 1840 mBeginSoftInputOnLongPressCommand = new BeginSoftInputOnLongPressCommand(); 1841 } else { 1842 removeCallbacks(mBeginSoftInputOnLongPressCommand); 1843 } 1844 postDelayed(mBeginSoftInputOnLongPressCommand, ViewConfiguration.getLongPressTimeout()); 1845 } 1846 1847 /** 1848 * Removes the command for beginning an edit of the current value via IME. 1849 */ 1850 private void removeBeginSoftInputCommand() { 1851 if (mBeginSoftInputOnLongPressCommand != null) { 1852 removeCallbacks(mBeginSoftInputOnLongPressCommand); 1853 } 1854 } 1855 1856 /** 1857 * Removes all pending callback from the message queue. 1858 */ 1859 private void removeAllCallbacks() { 1860 if (mChangeCurrentByOneFromLongPressCommand != null) { 1861 removeCallbacks(mChangeCurrentByOneFromLongPressCommand); 1862 } 1863 if (mSetSelectionCommand != null) { 1864 removeCallbacks(mSetSelectionCommand); 1865 } 1866 if (mBeginSoftInputOnLongPressCommand != null) { 1867 removeCallbacks(mBeginSoftInputOnLongPressCommand); 1868 } 1869 mPressedStateHelper.cancel(); 1870 } 1871 1872 /** 1873 * @return The selected index given its displayed <code>value</code>. 1874 */ 1875 private int getSelectedPos(String value) { 1876 if (mDisplayedValues == null) { 1877 try { 1878 return Integer.parseInt(value); 1879 } catch (NumberFormatException e) { 1880 // Ignore as if it's not a number we don't care 1881 } 1882 } else { 1883 for (int i = 0; i < mDisplayedValues.length; i++) { 1884 // Don't force the user to type in jan when ja will do 1885 value = value.toLowerCase(); 1886 if (mDisplayedValues[i].toLowerCase().startsWith(value)) { 1887 return mMinValue + i; 1888 } 1889 } 1890 1891 /* 1892 * The user might have typed in a number into the month field i.e. 1893 * 10 instead of OCT so support that too. 1894 */ 1895 try { 1896 return Integer.parseInt(value); 1897 } catch (NumberFormatException e) { 1898 1899 // Ignore as if it's not a number we don't care 1900 } 1901 } 1902 return mMinValue; 1903 } 1904 1905 /** 1906 * Posts an {@link SetSelectionCommand} from the given <code>selectionStart 1907 * </code> to <code>selectionEnd</code>. 1908 */ 1909 private void postSetSelectionCommand(int selectionStart, int selectionEnd) { 1910 if (mSetSelectionCommand == null) { 1911 mSetSelectionCommand = new SetSelectionCommand(); 1912 } else { 1913 removeCallbacks(mSetSelectionCommand); 1914 } 1915 mSetSelectionCommand.mSelectionStart = selectionStart; 1916 mSetSelectionCommand.mSelectionEnd = selectionEnd; 1917 post(mSetSelectionCommand); 1918 } 1919 1920 /** 1921 * The numbers accepted by the input text's {@link Filter} 1922 */ 1923 private static final char[] DIGIT_CHARACTERS = new char[] { 1924 // Latin digits are the common case 1925 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 1926 // Arabic-Indic 1927 '\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668' 1928 , '\u0669', 1929 // Extended Arabic-Indic 1930 '\u06f0', '\u06f1', '\u06f2', '\u06f3', '\u06f4', '\u06f5', '\u06f6', '\u06f7', '\u06f8' 1931 , '\u06f9' 1932 }; 1933 1934 /** 1935 * Filter for accepting only valid indices or prefixes of the string 1936 * representation of valid indices. 1937 */ 1938 class InputTextFilter extends NumberKeyListener { 1939 1940 // XXX This doesn't allow for range limits when controlled by a 1941 // soft input method! 1942 public int getInputType() { 1943 return InputType.TYPE_CLASS_TEXT; 1944 } 1945 1946 @Override 1947 protected char[] getAcceptedChars() { 1948 return DIGIT_CHARACTERS; 1949 } 1950 1951 @Override 1952 public CharSequence filter( 1953 CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 1954 if (mDisplayedValues == null) { 1955 CharSequence filtered = super.filter(source, start, end, dest, dstart, dend); 1956 if (filtered == null) { 1957 filtered = source.subSequence(start, end); 1958 } 1959 1960 String result = String.valueOf(dest.subSequence(0, dstart)) + filtered 1961 + dest.subSequence(dend, dest.length()); 1962 1963 if ("".equals(result)) { 1964 return result; 1965 } 1966 int val = getSelectedPos(result); 1967 1968 /* 1969 * Ensure the user can't type in a value greater than the max 1970 * allowed. We have to allow less than min as the user might 1971 * want to delete some numbers and then type a new number. 1972 */ 1973 if (val > mMaxValue) { 1974 return ""; 1975 } else { 1976 return filtered; 1977 } 1978 } else { 1979 CharSequence filtered = String.valueOf(source.subSequence(start, end)); 1980 if (TextUtils.isEmpty(filtered)) { 1981 return ""; 1982 } 1983 String result = String.valueOf(dest.subSequence(0, dstart)) + filtered 1984 + dest.subSequence(dend, dest.length()); 1985 String str = String.valueOf(result).toLowerCase(); 1986 for (String val : mDisplayedValues) { 1987 String valLowerCase = val.toLowerCase(); 1988 if (valLowerCase.startsWith(str)) { 1989 postSetSelectionCommand(result.length(), val.length()); 1990 return val.subSequence(dstart, val.length()); 1991 } 1992 } 1993 return ""; 1994 } 1995 } 1996 } 1997 1998 /** 1999 * Ensures that the scroll wheel is adjusted i.e. there is no offset and the 2000 * middle element is in the middle of the widget. 2001 * 2002 * @return Whether an adjustment has been made. 2003 */ 2004 private boolean ensureScrollWheelAdjusted() { 2005 // adjust to the closest value 2006 int deltaY = mInitialScrollOffset - mCurrentScrollOffset; 2007 if (deltaY != 0) { 2008 mPreviousScrollerY = 0; 2009 if (Math.abs(deltaY) > mSelectorElementHeight / 2) { 2010 deltaY += (deltaY > 0) ? -mSelectorElementHeight : mSelectorElementHeight; 2011 } 2012 mAdjustScroller.startScroll(0, 0, 0, deltaY, SELECTOR_ADJUSTMENT_DURATION_MILLIS); 2013 invalidate(); 2014 return true; 2015 } 2016 return false; 2017 } 2018 2019 class PressedStateHelper implements Runnable { 2020 public static final int BUTTON_INCREMENT = 1; 2021 public static final int BUTTON_DECREMENT = 2; 2022 2023 private final int MODE_PRESS = 1; 2024 private final int MODE_TAPPED = 2; 2025 2026 private int mManagedButton; 2027 private int mMode; 2028 2029 public void cancel() { 2030 mMode = 0; 2031 mManagedButton = 0; 2032 NumberPicker.this.removeCallbacks(this); 2033 if (mIncrementVirtualButtonPressed) { 2034 mIncrementVirtualButtonPressed = false; 2035 invalidate(0, mBottomSelectionDividerBottom, mRight, mBottom); 2036 } 2037 mDecrementVirtualButtonPressed = false; 2038 if (mDecrementVirtualButtonPressed) { 2039 invalidate(0, 0, mRight, mTopSelectionDividerTop); 2040 } 2041 } 2042 2043 public void buttonPressDelayed(int button) { 2044 cancel(); 2045 mMode = MODE_PRESS; 2046 mManagedButton = button; 2047 NumberPicker.this.postDelayed(this, ViewConfiguration.getTapTimeout()); 2048 } 2049 2050 public void buttonTapped(int button) { 2051 cancel(); 2052 mMode = MODE_TAPPED; 2053 mManagedButton = button; 2054 NumberPicker.this.post(this); 2055 } 2056 2057 @Override 2058 public void run() { 2059 switch (mMode) { 2060 case MODE_PRESS: { 2061 switch (mManagedButton) { 2062 case BUTTON_INCREMENT: { 2063 mIncrementVirtualButtonPressed = true; 2064 invalidate(0, mBottomSelectionDividerBottom, mRight, mBottom); 2065 } break; 2066 case BUTTON_DECREMENT: { 2067 mDecrementVirtualButtonPressed = true; 2068 invalidate(0, 0, mRight, mTopSelectionDividerTop); 2069 } 2070 } 2071 } break; 2072 case MODE_TAPPED: { 2073 switch (mManagedButton) { 2074 case BUTTON_INCREMENT: { 2075 if (!mIncrementVirtualButtonPressed) { 2076 NumberPicker.this.postDelayed(this, 2077 ViewConfiguration.getPressedStateDuration()); 2078 } 2079 mIncrementVirtualButtonPressed ^= true; 2080 invalidate(0, mBottomSelectionDividerBottom, mRight, mBottom); 2081 } break; 2082 case BUTTON_DECREMENT: { 2083 if (!mDecrementVirtualButtonPressed) { 2084 NumberPicker.this.postDelayed(this, 2085 ViewConfiguration.getPressedStateDuration()); 2086 } 2087 mDecrementVirtualButtonPressed ^= true; 2088 invalidate(0, 0, mRight, mTopSelectionDividerTop); 2089 } 2090 } 2091 } break; 2092 } 2093 } 2094 } 2095 2096 /** 2097 * Command for setting the input text selection. 2098 */ 2099 class SetSelectionCommand implements Runnable { 2100 private int mSelectionStart; 2101 2102 private int mSelectionEnd; 2103 2104 public void run() { 2105 mInputText.setSelection(mSelectionStart, mSelectionEnd); 2106 } 2107 } 2108 2109 /** 2110 * Command for changing the current value from a long press by one. 2111 */ 2112 class ChangeCurrentByOneFromLongPressCommand implements Runnable { 2113 private boolean mIncrement; 2114 2115 private void setStep(boolean increment) { 2116 mIncrement = increment; 2117 } 2118 2119 @Override 2120 public void run() { 2121 changeValueByOne(mIncrement); 2122 postDelayed(this, mLongPressUpdateInterval); 2123 } 2124 } 2125 2126 /** 2127 * @hide 2128 */ 2129 public static class CustomEditText extends EditText { 2130 2131 public CustomEditText(Context context, AttributeSet attrs) { 2132 super(context, attrs); 2133 } 2134 2135 @Override 2136 public void onEditorAction(int actionCode) { 2137 super.onEditorAction(actionCode); 2138 if (actionCode == EditorInfo.IME_ACTION_DONE) { 2139 clearFocus(); 2140 } 2141 } 2142 } 2143 2144 /** 2145 * Command for beginning soft input on long press. 2146 */ 2147 class BeginSoftInputOnLongPressCommand implements Runnable { 2148 2149 @Override 2150 public void run() { 2151 showSoftInput(); 2152 mIngonreMoveEvents = true; 2153 } 2154 } 2155 2156 /** 2157 * Class for managing virtual view tree rooted at this picker. 2158 */ 2159 class AccessibilityNodeProviderImpl extends AccessibilityNodeProvider { 2160 private static final int UNDEFINED = Integer.MIN_VALUE; 2161 2162 private static final int VIRTUAL_VIEW_ID_INCREMENT = 1; 2163 2164 private static final int VIRTUAL_VIEW_ID_INPUT = 2; 2165 2166 private static final int VIRTUAL_VIEW_ID_DECREMENT = 3; 2167 2168 private final Rect mTempRect = new Rect(); 2169 2170 private final int[] mTempArray = new int[2]; 2171 2172 private int mAccessibilityFocusedView = UNDEFINED; 2173 2174 @Override 2175 public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) { 2176 switch (virtualViewId) { 2177 case View.NO_ID: 2178 return createAccessibilityNodeInfoForNumberPicker( mScrollX, mScrollY, 2179 mScrollX + (mRight - mLeft), mScrollY + (mBottom - mTop)); 2180 case VIRTUAL_VIEW_ID_DECREMENT: 2181 return createAccessibilityNodeInfoForVirtualButton(VIRTUAL_VIEW_ID_DECREMENT, 2182 getVirtualDecrementButtonText(), mScrollX, mScrollY, 2183 mScrollX + (mRight - mLeft), 2184 mTopSelectionDividerTop + mSelectionDividerHeight); 2185 case VIRTUAL_VIEW_ID_INPUT: 2186 return createAccessibiltyNodeInfoForInputText(); 2187 case VIRTUAL_VIEW_ID_INCREMENT: 2188 return createAccessibilityNodeInfoForVirtualButton(VIRTUAL_VIEW_ID_INCREMENT, 2189 getVirtualIncrementButtonText(), mScrollX, 2190 mBottomSelectionDividerBottom - mSelectionDividerHeight, 2191 mScrollX + (mRight - mLeft), mScrollY + (mBottom - mTop)); 2192 } 2193 return super.createAccessibilityNodeInfo(virtualViewId); 2194 } 2195 2196 @Override 2197 public List<AccessibilityNodeInfo> findAccessibilityNodeInfosByText(String searched, 2198 int virtualViewId) { 2199 if (TextUtils.isEmpty(searched)) { 2200 return Collections.emptyList(); 2201 } 2202 String searchedLowerCase = searched.toLowerCase(); 2203 List<AccessibilityNodeInfo> result = new ArrayList<AccessibilityNodeInfo>(); 2204 switch (virtualViewId) { 2205 case View.NO_ID: { 2206 findAccessibilityNodeInfosByTextInChild(searchedLowerCase, 2207 VIRTUAL_VIEW_ID_DECREMENT, result); 2208 findAccessibilityNodeInfosByTextInChild(searchedLowerCase, 2209 VIRTUAL_VIEW_ID_INPUT, result); 2210 findAccessibilityNodeInfosByTextInChild(searchedLowerCase, 2211 VIRTUAL_VIEW_ID_INCREMENT, result); 2212 return result; 2213 } 2214 case VIRTUAL_VIEW_ID_DECREMENT: 2215 case VIRTUAL_VIEW_ID_INCREMENT: 2216 case VIRTUAL_VIEW_ID_INPUT: { 2217 findAccessibilityNodeInfosByTextInChild(searchedLowerCase, virtualViewId, 2218 result); 2219 return result; 2220 } 2221 } 2222 return super.findAccessibilityNodeInfosByText(searched, virtualViewId); 2223 } 2224 2225 @Override 2226 public boolean performAction(int virtualViewId, int action, Bundle arguments) { 2227 switch (virtualViewId) { 2228 case View.NO_ID: { 2229 switch (action) { 2230 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 2231 if (mAccessibilityFocusedView != virtualViewId) { 2232 mAccessibilityFocusedView = virtualViewId; 2233 requestAccessibilityFocus(); 2234 return true; 2235 } 2236 } return false; 2237 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 2238 if (mAccessibilityFocusedView == virtualViewId) { 2239 mAccessibilityFocusedView = UNDEFINED; 2240 clearAccessibilityFocus(); 2241 return true; 2242 } 2243 return false; 2244 } 2245 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: { 2246 if (NumberPicker.this.isEnabled() 2247 && (getWrapSelectorWheel() || getValue() < getMaxValue())) { 2248 changeValueByOne(true); 2249 return true; 2250 } 2251 } return false; 2252 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: { 2253 if (NumberPicker.this.isEnabled() 2254 && (getWrapSelectorWheel() || getValue() > getMinValue())) { 2255 changeValueByOne(false); 2256 return true; 2257 } 2258 } return false; 2259 } 2260 } break; 2261 case VIRTUAL_VIEW_ID_INPUT: { 2262 switch (action) { 2263 case AccessibilityNodeInfo.ACTION_FOCUS: { 2264 if (NumberPicker.this.isEnabled() && !mInputText.isFocused()) { 2265 return mInputText.requestFocus(); 2266 } 2267 } break; 2268 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 2269 if (NumberPicker.this.isEnabled() && mInputText.isFocused()) { 2270 mInputText.clearFocus(); 2271 return true; 2272 } 2273 return false; 2274 } 2275 case AccessibilityNodeInfo.ACTION_CLICK: { 2276 if (NumberPicker.this.isEnabled()) { 2277 showSoftInput(); 2278 return true; 2279 } 2280 return false; 2281 } 2282 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 2283 if (mAccessibilityFocusedView != virtualViewId) { 2284 mAccessibilityFocusedView = virtualViewId; 2285 sendAccessibilityEventForVirtualView(virtualViewId, 2286 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 2287 mInputText.invalidate(); 2288 return true; 2289 } 2290 } return false; 2291 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 2292 if (mAccessibilityFocusedView == virtualViewId) { 2293 mAccessibilityFocusedView = UNDEFINED; 2294 sendAccessibilityEventForVirtualView(virtualViewId, 2295 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 2296 mInputText.invalidate(); 2297 return true; 2298 } 2299 } return false; 2300 default: { 2301 return mInputText.performAccessibilityAction(action, arguments); 2302 } 2303 } 2304 } return false; 2305 case VIRTUAL_VIEW_ID_INCREMENT: { 2306 switch (action) { 2307 case AccessibilityNodeInfo.ACTION_CLICK: { 2308 if (NumberPicker.this.isEnabled()) { 2309 NumberPicker.this.changeValueByOne(true); 2310 sendAccessibilityEventForVirtualView(virtualViewId, 2311 AccessibilityEvent.TYPE_VIEW_CLICKED); 2312 return true; 2313 } 2314 } return false; 2315 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 2316 if (mAccessibilityFocusedView != virtualViewId) { 2317 mAccessibilityFocusedView = virtualViewId; 2318 sendAccessibilityEventForVirtualView(virtualViewId, 2319 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 2320 invalidate(0, mBottomSelectionDividerBottom, mRight, mBottom); 2321 return true; 2322 } 2323 } return false; 2324 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 2325 if (mAccessibilityFocusedView == virtualViewId) { 2326 mAccessibilityFocusedView = UNDEFINED; 2327 sendAccessibilityEventForVirtualView(virtualViewId, 2328 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 2329 invalidate(0, mBottomSelectionDividerBottom, mRight, mBottom); 2330 return true; 2331 } 2332 } return false; 2333 } 2334 } return false; 2335 case VIRTUAL_VIEW_ID_DECREMENT: { 2336 switch (action) { 2337 case AccessibilityNodeInfo.ACTION_CLICK: { 2338 if (NumberPicker.this.isEnabled()) { 2339 final boolean increment = (virtualViewId == VIRTUAL_VIEW_ID_INCREMENT); 2340 NumberPicker.this.changeValueByOne(increment); 2341 sendAccessibilityEventForVirtualView(virtualViewId, 2342 AccessibilityEvent.TYPE_VIEW_CLICKED); 2343 return true; 2344 } 2345 } return false; 2346 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 2347 if (mAccessibilityFocusedView != virtualViewId) { 2348 mAccessibilityFocusedView = virtualViewId; 2349 sendAccessibilityEventForVirtualView(virtualViewId, 2350 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 2351 invalidate(0, 0, mRight, mTopSelectionDividerTop); 2352 return true; 2353 } 2354 } return false; 2355 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 2356 if (mAccessibilityFocusedView == virtualViewId) { 2357 mAccessibilityFocusedView = UNDEFINED; 2358 sendAccessibilityEventForVirtualView(virtualViewId, 2359 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 2360 invalidate(0, 0, mRight, mTopSelectionDividerTop); 2361 return true; 2362 } 2363 } return false; 2364 } 2365 } return false; 2366 } 2367 return super.performAction(virtualViewId, action, arguments); 2368 } 2369 2370 public void sendAccessibilityEventForVirtualView(int virtualViewId, int eventType) { 2371 switch (virtualViewId) { 2372 case VIRTUAL_VIEW_ID_DECREMENT: { 2373 if (hasVirtualDecrementButton()) { 2374 sendAccessibilityEventForVirtualButton(virtualViewId, eventType, 2375 getVirtualDecrementButtonText()); 2376 } 2377 } break; 2378 case VIRTUAL_VIEW_ID_INPUT: { 2379 sendAccessibilityEventForVirtualText(eventType); 2380 } break; 2381 case VIRTUAL_VIEW_ID_INCREMENT: { 2382 if (hasVirtualIncrementButton()) { 2383 sendAccessibilityEventForVirtualButton(virtualViewId, eventType, 2384 getVirtualIncrementButtonText()); 2385 } 2386 } break; 2387 } 2388 } 2389 2390 private void sendAccessibilityEventForVirtualText(int eventType) { 2391 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 2392 AccessibilityEvent event = AccessibilityEvent.obtain(eventType); 2393 mInputText.onInitializeAccessibilityEvent(event); 2394 mInputText.onPopulateAccessibilityEvent(event); 2395 event.setSource(NumberPicker.this, VIRTUAL_VIEW_ID_INPUT); 2396 requestSendAccessibilityEvent(NumberPicker.this, event); 2397 } 2398 } 2399 2400 private void sendAccessibilityEventForVirtualButton(int virtualViewId, int eventType, 2401 String text) { 2402 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 2403 AccessibilityEvent event = AccessibilityEvent.obtain(eventType); 2404 event.setClassName(Button.class.getName()); 2405 event.setPackageName(mContext.getPackageName()); 2406 event.getText().add(text); 2407 event.setEnabled(NumberPicker.this.isEnabled()); 2408 event.setSource(NumberPicker.this, virtualViewId); 2409 requestSendAccessibilityEvent(NumberPicker.this, event); 2410 } 2411 } 2412 2413 private void findAccessibilityNodeInfosByTextInChild(String searchedLowerCase, 2414 int virtualViewId, List<AccessibilityNodeInfo> outResult) { 2415 switch (virtualViewId) { 2416 case VIRTUAL_VIEW_ID_DECREMENT: { 2417 String text = getVirtualDecrementButtonText(); 2418 if (!TextUtils.isEmpty(text) 2419 && text.toString().toLowerCase().contains(searchedLowerCase)) { 2420 outResult.add(createAccessibilityNodeInfo(VIRTUAL_VIEW_ID_DECREMENT)); 2421 } 2422 } return; 2423 case VIRTUAL_VIEW_ID_INPUT: { 2424 CharSequence text = mInputText.getText(); 2425 if (!TextUtils.isEmpty(text) && 2426 text.toString().toLowerCase().contains(searchedLowerCase)) { 2427 outResult.add(createAccessibilityNodeInfo(VIRTUAL_VIEW_ID_INPUT)); 2428 return; 2429 } 2430 CharSequence contentDesc = mInputText.getText(); 2431 if (!TextUtils.isEmpty(contentDesc) && 2432 contentDesc.toString().toLowerCase().contains(searchedLowerCase)) { 2433 outResult.add(createAccessibilityNodeInfo(VIRTUAL_VIEW_ID_INPUT)); 2434 return; 2435 } 2436 } break; 2437 case VIRTUAL_VIEW_ID_INCREMENT: { 2438 String text = getVirtualIncrementButtonText(); 2439 if (!TextUtils.isEmpty(text) 2440 && text.toString().toLowerCase().contains(searchedLowerCase)) { 2441 outResult.add(createAccessibilityNodeInfo(VIRTUAL_VIEW_ID_INCREMENT)); 2442 } 2443 } return; 2444 } 2445 } 2446 2447 private AccessibilityNodeInfo createAccessibiltyNodeInfoForInputText() { 2448 AccessibilityNodeInfo info = mInputText.createAccessibilityNodeInfo(); 2449 info.setSource(NumberPicker.this, VIRTUAL_VIEW_ID_INPUT); 2450 if (mAccessibilityFocusedView != VIRTUAL_VIEW_ID_INPUT) { 2451 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 2452 } 2453 if (mAccessibilityFocusedView == VIRTUAL_VIEW_ID_INPUT) { 2454 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 2455 } 2456 return info; 2457 } 2458 2459 private AccessibilityNodeInfo createAccessibilityNodeInfoForVirtualButton(int virtualViewId, 2460 String text, int left, int top, int right, int bottom) { 2461 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(); 2462 info.setClassName(Button.class.getName()); 2463 info.setPackageName(mContext.getPackageName()); 2464 info.setSource(NumberPicker.this, virtualViewId); 2465 info.setParent(NumberPicker.this); 2466 info.setText(text); 2467 info.setClickable(true); 2468 info.setLongClickable(true); 2469 info.setEnabled(NumberPicker.this.isEnabled()); 2470 Rect boundsInParent = mTempRect; 2471 boundsInParent.set(left, top, right, bottom); 2472 info.setVisibleToUser(isVisibleToUser(boundsInParent)); 2473 info.setBoundsInParent(boundsInParent); 2474 Rect boundsInScreen = boundsInParent; 2475 int[] locationOnScreen = mTempArray; 2476 getLocationOnScreen(locationOnScreen); 2477 boundsInScreen.offset(locationOnScreen[0], locationOnScreen[1]); 2478 info.setBoundsInScreen(boundsInScreen); 2479 2480 if (mAccessibilityFocusedView != virtualViewId) { 2481 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 2482 } 2483 if (mAccessibilityFocusedView == virtualViewId) { 2484 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 2485 } 2486 if (NumberPicker.this.isEnabled()) { 2487 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 2488 } 2489 2490 return info; 2491 } 2492 2493 private AccessibilityNodeInfo createAccessibilityNodeInfoForNumberPicker(int left, int top, 2494 int right, int bottom) { 2495 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(); 2496 info.setClassName(NumberPicker.class.getName()); 2497 info.setPackageName(mContext.getPackageName()); 2498 info.setSource(NumberPicker.this); 2499 2500 if (hasVirtualDecrementButton()) { 2501 info.addChild(NumberPicker.this, VIRTUAL_VIEW_ID_DECREMENT); 2502 } 2503 info.addChild(NumberPicker.this, VIRTUAL_VIEW_ID_INPUT); 2504 if (hasVirtualIncrementButton()) { 2505 info.addChild(NumberPicker.this, VIRTUAL_VIEW_ID_INCREMENT); 2506 } 2507 2508 info.setParent((View) getParentForAccessibility()); 2509 info.setEnabled(NumberPicker.this.isEnabled()); 2510 info.setScrollable(true); 2511 2512 final float applicationScale = 2513 getContext().getResources().getCompatibilityInfo().applicationScale; 2514 2515 Rect boundsInParent = mTempRect; 2516 boundsInParent.set(left, top, right, bottom); 2517 boundsInParent.scale(applicationScale); 2518 info.setBoundsInParent(boundsInParent); 2519 2520 info.setVisibleToUser(isVisibleToUser()); 2521 2522 Rect boundsInScreen = boundsInParent; 2523 int[] locationOnScreen = mTempArray; 2524 getLocationOnScreen(locationOnScreen); 2525 boundsInScreen.offset(locationOnScreen[0], locationOnScreen[1]); 2526 boundsInScreen.scale(applicationScale); 2527 info.setBoundsInScreen(boundsInScreen); 2528 2529 if (mAccessibilityFocusedView != View.NO_ID) { 2530 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 2531 } 2532 if (mAccessibilityFocusedView == View.NO_ID) { 2533 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 2534 } 2535 if (NumberPicker.this.isEnabled()) { 2536 if (getWrapSelectorWheel() || getValue() < getMaxValue()) { 2537 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); 2538 } 2539 if (getWrapSelectorWheel() || getValue() > getMinValue()) { 2540 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); 2541 } 2542 } 2543 2544 return info; 2545 } 2546 2547 private boolean hasVirtualDecrementButton() { 2548 return getWrapSelectorWheel() || getValue() > getMinValue(); 2549 } 2550 2551 private boolean hasVirtualIncrementButton() { 2552 return getWrapSelectorWheel() || getValue() < getMaxValue(); 2553 } 2554 2555 private String getVirtualDecrementButtonText() { 2556 int value = mValue - 1; 2557 if (mWrapSelectorWheel) { 2558 value = getWrappedSelectorIndex(value); 2559 } 2560 if (value >= mMinValue) { 2561 return (mDisplayedValues == null) ? formatNumber(value) 2562 : mDisplayedValues[value - mMinValue]; 2563 } 2564 return null; 2565 } 2566 2567 private String getVirtualIncrementButtonText() { 2568 int value = mValue + 1; 2569 if (mWrapSelectorWheel) { 2570 value = getWrappedSelectorIndex(value); 2571 } 2572 if (value <= mMaxValue) { 2573 return (mDisplayedValues == null) ? formatNumber(value) 2574 : mDisplayedValues[value - mMinValue]; 2575 } 2576 return null; 2577 } 2578 } 2579 2580 static private String formatNumberWithLocale(int value) { 2581 return String.format(Locale.getDefault(), "%d", value); 2582 } 2583} 2584