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