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