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