NumberPicker.java revision 644053466018c08e326787b909a76355bad1dd30
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.animation.Animator; 20import android.animation.AnimatorListenerAdapter; 21import android.animation.AnimatorSet; 22import android.animation.ObjectAnimator; 23import android.annotation.Widget; 24import android.content.Context; 25import android.content.res.ColorStateList; 26import android.content.res.TypedArray; 27import android.graphics.Canvas; 28import android.graphics.Color; 29import android.graphics.Paint; 30import android.graphics.Paint.Align; 31import android.graphics.Rect; 32import android.graphics.drawable.Drawable; 33import android.text.InputFilter; 34import android.text.InputType; 35import android.text.Spanned; 36import android.text.TextUtils; 37import android.text.method.NumberKeyListener; 38import android.util.AttributeSet; 39import android.util.SparseArray; 40import android.util.TypedValue; 41import android.view.KeyEvent; 42import android.view.LayoutInflater; 43import android.view.LayoutInflater.Filter; 44import android.view.MotionEvent; 45import android.view.VelocityTracker; 46import android.view.View; 47import android.view.ViewConfiguration; 48import android.view.accessibility.AccessibilityEvent; 49import android.view.accessibility.AccessibilityManager; 50import android.view.animation.DecelerateInterpolator; 51import android.view.inputmethod.InputMethodManager; 52 53import com.android.internal.R; 54 55/** 56 * A widget that enables the user to select a number form a predefined range. 57 * The widget presents an input field and up and down buttons for selecting the 58 * current value. Pressing/long-pressing the up and down buttons increments and 59 * decrements the current value respectively. Touching the input field shows a 60 * scroll wheel, which when touched allows direct edit 61 * of the current value. Sliding gestures up or down hide the buttons and the 62 * input filed, show and rotates the scroll wheel. Flinging is 63 * also supported. The widget enables mapping from positions to strings such 64 * that, instead of the position index, the corresponding string is displayed. 65 * <p> 66 * For an example of using this widget, see {@link android.widget.TimePicker}. 67 * </p> 68 */ 69@Widget 70public class NumberPicker extends LinearLayout { 71 72 /** 73 * The default update interval during long press. 74 */ 75 private static final long DEFAULT_LONG_PRESS_UPDATE_INTERVAL = 300; 76 77 /** 78 * The index of the middle selector item. 79 */ 80 private static final int SELECTOR_MIDDLE_ITEM_INDEX = 2; 81 82 /** 83 * The coefficient by which to adjust (divide) the max fling velocity. 84 */ 85 private static final int SELECTOR_MAX_FLING_VELOCITY_ADJUSTMENT = 8; 86 87 /** 88 * The the duration for adjusting the selector wheel. 89 */ 90 private static final int SELECTOR_ADJUSTMENT_DURATION_MILLIS = 800; 91 92 /** 93 * The duration of scrolling to the next/previous value while changing 94 * the current value by one, i.e. increment or decrement. 95 */ 96 private static final int CHANGE_CURRENT_BY_ONE_SCROLL_DURATION = 300; 97 98 /** 99 * The the delay for showing the input controls after a single tap on the 100 * input text. 101 */ 102 private static final int SHOW_INPUT_CONTROLS_DELAY_MILLIS = ViewConfiguration 103 .getDoubleTapTimeout(); 104 105 /** 106 * The strength of fading in the top and bottom while drawing the selector. 107 */ 108 private static final float TOP_AND_BOTTOM_FADING_EDGE_STRENGTH = 0.9f; 109 110 /** 111 * The default unscaled height of the selection divider. 112 */ 113 private static final int UNSCALED_DEFAULT_SELECTION_DIVIDER_HEIGHT = 2; 114 115 /** 116 * In this state the selector wheel is not shown. 117 */ 118 private static final int SELECTOR_WHEEL_STATE_NONE = 0; 119 120 /** 121 * In this state the selector wheel is small. 122 */ 123 private static final int SELECTOR_WHEEL_STATE_SMALL = 1; 124 125 /** 126 * In this state the selector wheel is large. 127 */ 128 private static final int SELECTOR_WHEEL_STATE_LARGE = 2; 129 130 /** 131 * The alpha of the selector wheel when it is bright. 132 */ 133 private static final int SELECTOR_WHEEL_BRIGHT_ALPHA = 255; 134 135 /** 136 * The alpha of the selector wheel when it is dimmed. 137 */ 138 private static final int SELECTOR_WHEEL_DIM_ALPHA = 60; 139 140 /** 141 * The alpha for the increment/decrement button when it is transparent. 142 */ 143 private static final int BUTTON_ALPHA_TRANSPARENT = 0; 144 145 /** 146 * The alpha for the increment/decrement button when it is opaque. 147 */ 148 private static final int BUTTON_ALPHA_OPAQUE = 1; 149 150 /** 151 * The property for setting the selector paint. 152 */ 153 private static final String PROPERTY_SELECTOR_PAINT_ALPHA = "selectorPaintAlpha"; 154 155 /** 156 * The property for setting the increment/decrement button alpha. 157 */ 158 private static final String PROPERTY_BUTTON_ALPHA = "alpha"; 159 160 /** 161 * The numbers accepted by the input text's {@link Filter} 162 */ 163 private static final char[] DIGIT_CHARACTERS = new char[] { 164 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' 165 }; 166 167 /** 168 * Constant for unspecified size. 169 */ 170 private static final int SIZE_UNSPECIFIED = -1; 171 172 /** 173 * Use a custom NumberPicker formatting callback to use two-digit minutes 174 * strings like "01". Keeping a static formatter etc. is the most efficient 175 * way to do this; it avoids creating temporary objects on every call to 176 * format(). 177 * 178 * @hide 179 */ 180 public static final NumberPicker.Formatter TWO_DIGIT_FORMATTER = new NumberPicker.Formatter() { 181 final StringBuilder mBuilder = new StringBuilder(); 182 183 final java.util.Formatter mFmt = new java.util.Formatter(mBuilder, java.util.Locale.US); 184 185 final Object[] mArgs = new Object[1]; 186 187 public String format(int value) { 188 mArgs[0] = value; 189 mBuilder.delete(0, mBuilder.length()); 190 mFmt.format("%02d", mArgs); 191 return mFmt.toString(); 192 } 193 }; 194 195 /** 196 * The increment button. 197 */ 198 private final ImageButton mIncrementButton; 199 200 /** 201 * The decrement button. 202 */ 203 private final ImageButton mDecrementButton; 204 205 /** 206 * The text for showing the current value. 207 */ 208 private final EditText mInputText; 209 210 /** 211 * The min height of this widget. 212 */ 213 private final int mMinHeight; 214 215 /** 216 * The max height of this widget. 217 */ 218 private final int mMaxHeight; 219 220 /** 221 * The max width of this widget. 222 */ 223 private final int mMinWidth; 224 225 /** 226 * The max width of this widget. 227 */ 228 private int mMaxWidth; 229 230 /** 231 * Flag whether to compute the max width. 232 */ 233 private final boolean mComputeMaxWidth; 234 235 /** 236 * The height of the text. 237 */ 238 private final int mTextSize; 239 240 /** 241 * The height of the gap between text elements if the selector wheel. 242 */ 243 private int mSelectorTextGapHeight; 244 245 /** 246 * The values to be displayed instead the indices. 247 */ 248 private String[] mDisplayedValues; 249 250 /** 251 * Lower value of the range of numbers allowed for the NumberPicker 252 */ 253 private int mMinValue; 254 255 /** 256 * Upper value of the range of numbers allowed for the NumberPicker 257 */ 258 private int mMaxValue; 259 260 /** 261 * Current value of this NumberPicker 262 */ 263 private int mValue; 264 265 /** 266 * Listener to be notified upon current value change. 267 */ 268 private OnValueChangeListener mOnValueChangeListener; 269 270 /** 271 * Listener to be notified upon scroll state change. 272 */ 273 private OnScrollListener mOnScrollListener; 274 275 /** 276 * Formatter for for displaying the current value. 277 */ 278 private Formatter mFormatter; 279 280 /** 281 * The speed for updating the value form long press. 282 */ 283 private long mLongPressUpdateInterval = DEFAULT_LONG_PRESS_UPDATE_INTERVAL; 284 285 /** 286 * Cache for the string representation of selector indices. 287 */ 288 private final SparseArray<String> mSelectorIndexToStringCache = new SparseArray<String>(); 289 290 /** 291 * The selector indices whose value are show by the selector. 292 */ 293 private final int[] mSelectorIndices = new int[] { 294 Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, 295 Integer.MIN_VALUE 296 }; 297 298 /** 299 * The {@link Paint} for drawing the selector. 300 */ 301 private final Paint mSelectorWheelPaint; 302 303 /** 304 * The height of a selector element (text + gap). 305 */ 306 private int mSelectorElementHeight; 307 308 /** 309 * The initial offset of the scroll selector. 310 */ 311 private int mInitialScrollOffset = Integer.MIN_VALUE; 312 313 /** 314 * The current offset of the scroll selector. 315 */ 316 private int mCurrentScrollOffset; 317 318 /** 319 * The {@link Scroller} responsible for flinging the selector. 320 */ 321 private final Scroller mFlingScroller; 322 323 /** 324 * The {@link Scroller} responsible for adjusting the selector. 325 */ 326 private final Scroller mAdjustScroller; 327 328 /** 329 * The previous Y coordinate while scrolling the selector. 330 */ 331 private int mPreviousScrollerY; 332 333 /** 334 * Handle to the reusable command for setting the input text selection. 335 */ 336 private SetSelectionCommand mSetSelectionCommand; 337 338 /** 339 * Handle to the reusable command for adjusting the scroller. 340 */ 341 private AdjustScrollerCommand mAdjustScrollerCommand; 342 343 /** 344 * Handle to the reusable command for changing the current value from long 345 * press by one. 346 */ 347 private ChangeCurrentByOneFromLongPressCommand mChangeCurrentByOneFromLongPressCommand; 348 349 /** 350 * {@link Animator} for showing the up/down arrows. 351 */ 352 private final AnimatorSet mShowInputControlsAnimator; 353 354 /** 355 * {@link Animator} for dimming the selector wheel. 356 */ 357 private final Animator mDimSelectorWheelAnimator; 358 359 /** 360 * The Y position of the last down event. 361 */ 362 private float mLastDownEventY; 363 364 /** 365 * The Y position of the last motion event. 366 */ 367 private float mLastMotionEventY; 368 369 /** 370 * Flag if to begin edit on next up event. 371 */ 372 private boolean mBeginEditOnUpEvent; 373 374 /** 375 * Flag if to adjust the selector wheel on next up event. 376 */ 377 private boolean mAdjustScrollerOnUpEvent; 378 379 /** 380 * The state of the selector wheel. 381 */ 382 private int mSelectorWheelState; 383 384 /** 385 * Determines speed during touch scrolling. 386 */ 387 private VelocityTracker mVelocityTracker; 388 389 /** 390 * @see ViewConfiguration#getScaledTouchSlop() 391 */ 392 private int mTouchSlop; 393 394 /** 395 * @see ViewConfiguration#getScaledMinimumFlingVelocity() 396 */ 397 private int mMinimumFlingVelocity; 398 399 /** 400 * @see ViewConfiguration#getScaledMaximumFlingVelocity() 401 */ 402 private int mMaximumFlingVelocity; 403 404 /** 405 * Flag whether the selector should wrap around. 406 */ 407 private boolean mWrapSelectorWheel; 408 409 /** 410 * The back ground color used to optimize scroller fading. 411 */ 412 private final int mSolidColor; 413 414 /** 415 * Flag indicating if this widget supports flinging. 416 */ 417 private final boolean mFlingable; 418 419 /** 420 * Divider for showing item to be selected while scrolling 421 */ 422 private final Drawable mSelectionDivider; 423 424 /** 425 * The height of the selection divider. 426 */ 427 private final int mSelectionDividerHeight; 428 429 /** 430 * Reusable {@link Rect} instance. 431 */ 432 private final Rect mTempRect = new Rect(); 433 434 /** 435 * The current scroll state of the number picker. 436 */ 437 private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE; 438 439 /** 440 * The duration of the animation for showing the input controls. 441 */ 442 private final long mShowInputControlsAnimimationDuration; 443 444 /** 445 * Flag whether the scoll wheel and the fading edges have been initialized. 446 */ 447 private boolean mScrollWheelAndFadingEdgesInitialized; 448 449 /** 450 * Interface to listen for changes of the current value. 451 */ 452 public interface OnValueChangeListener { 453 454 /** 455 * Called upon a change of the current value. 456 * 457 * @param picker The NumberPicker associated with this listener. 458 * @param oldVal The previous value. 459 * @param newVal The new value. 460 */ 461 void onValueChange(NumberPicker picker, int oldVal, int newVal); 462 } 463 464 /** 465 * Interface to listen for the picker scroll state. 466 */ 467 public interface OnScrollListener { 468 469 /** 470 * The view is not scrolling. 471 */ 472 public static int SCROLL_STATE_IDLE = 0; 473 474 /** 475 * The user is scrolling using touch, and their finger is still on the screen. 476 */ 477 public static int SCROLL_STATE_TOUCH_SCROLL = 1; 478 479 /** 480 * The user had previously been scrolling using touch and performed a fling. 481 */ 482 public static int SCROLL_STATE_FLING = 2; 483 484 /** 485 * Callback invoked while the number picker scroll state has changed. 486 * 487 * @param view The view whose scroll state is being reported. 488 * @param scrollState The current scroll state. One of 489 * {@link #SCROLL_STATE_IDLE}, 490 * {@link #SCROLL_STATE_TOUCH_SCROLL} or 491 * {@link #SCROLL_STATE_IDLE}. 492 */ 493 public void onScrollStateChange(NumberPicker view, int scrollState); 494 } 495 496 /** 497 * Interface used to format current value into a string for presentation. 498 */ 499 public interface Formatter { 500 501 /** 502 * Formats a string representation of the current value. 503 * 504 * @param value The currently selected value. 505 * @return A formatted string representation. 506 */ 507 public String format(int value); 508 } 509 510 /** 511 * Create a new number picker. 512 * 513 * @param context The application environment. 514 */ 515 public NumberPicker(Context context) { 516 this(context, null); 517 } 518 519 /** 520 * Create a new number picker. 521 * 522 * @param context The application environment. 523 * @param attrs A collection of attributes. 524 */ 525 public NumberPicker(Context context, AttributeSet attrs) { 526 this(context, attrs, R.attr.numberPickerStyle); 527 } 528 529 /** 530 * Create a new number picker 531 * 532 * @param context the application environment. 533 * @param attrs a collection of attributes. 534 * @param defStyle The default style to apply to this view. 535 */ 536 public NumberPicker(Context context, AttributeSet attrs, int defStyle) { 537 super(context, attrs, defStyle); 538 539 // process style attributes 540 TypedArray attributesArray = context.obtainStyledAttributes(attrs, 541 R.styleable.NumberPicker, defStyle, 0); 542 mSolidColor = attributesArray.getColor(R.styleable.NumberPicker_solidColor, 0); 543 mFlingable = attributesArray.getBoolean(R.styleable.NumberPicker_flingable, true); 544 mSelectionDivider = attributesArray.getDrawable(R.styleable.NumberPicker_selectionDivider); 545 int defSelectionDividerHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 546 UNSCALED_DEFAULT_SELECTION_DIVIDER_HEIGHT, 547 getResources().getDisplayMetrics()); 548 mSelectionDividerHeight = attributesArray.getDimensionPixelSize( 549 R.styleable.NumberPicker_selectionDividerHeight, defSelectionDividerHeight); 550 mMinHeight = attributesArray.getDimensionPixelSize(R.styleable.NumberPicker_minHeight, 551 SIZE_UNSPECIFIED); 552 mMaxHeight = attributesArray.getDimensionPixelSize(R.styleable.NumberPicker_maxHeight, 553 SIZE_UNSPECIFIED); 554 if (mMinHeight != SIZE_UNSPECIFIED && mMaxHeight != SIZE_UNSPECIFIED 555 && mMinHeight > mMaxHeight) { 556 throw new IllegalArgumentException("minHeight > maxHeight"); 557 } 558 mMinWidth = attributesArray.getDimensionPixelSize(R.styleable.NumberPicker_minWidth, 559 SIZE_UNSPECIFIED); 560 mMaxWidth = attributesArray.getDimensionPixelSize(R.styleable.NumberPicker_maxWidth, 561 SIZE_UNSPECIFIED); 562 if (mMinWidth != SIZE_UNSPECIFIED && mMaxWidth != SIZE_UNSPECIFIED 563 && mMinWidth > mMaxWidth) { 564 throw new IllegalArgumentException("minWidth > maxWidth"); 565 } 566 mComputeMaxWidth = (mMaxWidth == Integer.MAX_VALUE); 567 attributesArray.recycle(); 568 569 mShowInputControlsAnimimationDuration = getResources().getInteger( 570 R.integer.config_longAnimTime); 571 572 // By default Linearlayout that we extend is not drawn. This is 573 // its draw() method is not called but dispatchDraw() is called 574 // directly (see ViewGroup.drawChild()). However, this class uses 575 // the fading edge effect implemented by View and we need our 576 // draw() method to be called. Therefore, we declare we will draw. 577 setWillNotDraw(false); 578 setSelectorWheelState(SELECTOR_WHEEL_STATE_NONE); 579 580 LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( 581 Context.LAYOUT_INFLATER_SERVICE); 582 inflater.inflate(R.layout.number_picker, this, true); 583 584 OnClickListener onClickListener = new OnClickListener() { 585 public void onClick(View v) { 586 InputMethodManager inputMethodManager = InputMethodManager.peekInstance(); 587 if (inputMethodManager != null && inputMethodManager.isActive(mInputText)) { 588 inputMethodManager.hideSoftInputFromWindow(getWindowToken(), 0); 589 } 590 mInputText.clearFocus(); 591 if (v.getId() == R.id.increment) { 592 changeCurrentByOne(true); 593 } else { 594 changeCurrentByOne(false); 595 } 596 } 597 }; 598 599 OnLongClickListener onLongClickListener = new OnLongClickListener() { 600 public boolean onLongClick(View v) { 601 mInputText.clearFocus(); 602 if (v.getId() == R.id.increment) { 603 postChangeCurrentByOneFromLongPress(true); 604 } else { 605 postChangeCurrentByOneFromLongPress(false); 606 } 607 return true; 608 } 609 }; 610 611 // increment button 612 mIncrementButton = (ImageButton) findViewById(R.id.increment); 613 mIncrementButton.setOnClickListener(onClickListener); 614 mIncrementButton.setOnLongClickListener(onLongClickListener); 615 616 // decrement button 617 mDecrementButton = (ImageButton) findViewById(R.id.decrement); 618 mDecrementButton.setOnClickListener(onClickListener); 619 mDecrementButton.setOnLongClickListener(onLongClickListener); 620 621 // input text 622 mInputText = (EditText) findViewById(R.id.numberpicker_input); 623 mInputText.setOnFocusChangeListener(new OnFocusChangeListener() { 624 public void onFocusChange(View v, boolean hasFocus) { 625 if (hasFocus) { 626 mInputText.selectAll(); 627 InputMethodManager inputMethodManager = InputMethodManager.peekInstance(); 628 if (inputMethodManager != null) { 629 inputMethodManager.showSoftInput(mInputText, 0); 630 } 631 } else { 632 mInputText.setSelection(0, 0); 633 validateInputTextView(v); 634 } 635 } 636 }); 637 mInputText.setFilters(new InputFilter[] { 638 new InputTextFilter() 639 }); 640 641 mInputText.setRawInputType(InputType.TYPE_CLASS_NUMBER); 642 643 // initialize constants 644 mTouchSlop = ViewConfiguration.getTapTimeout(); 645 ViewConfiguration configuration = ViewConfiguration.get(context); 646 mTouchSlop = configuration.getScaledTouchSlop(); 647 mMinimumFlingVelocity = configuration.getScaledMinimumFlingVelocity(); 648 mMaximumFlingVelocity = configuration.getScaledMaximumFlingVelocity() 649 / SELECTOR_MAX_FLING_VELOCITY_ADJUSTMENT; 650 mTextSize = (int) mInputText.getTextSize(); 651 652 // create the selector wheel paint 653 Paint paint = new Paint(); 654 paint.setAntiAlias(true); 655 paint.setTextAlign(Align.CENTER); 656 paint.setTextSize(mTextSize); 657 paint.setTypeface(mInputText.getTypeface()); 658 ColorStateList colors = mInputText.getTextColors(); 659 int color = colors.getColorForState(ENABLED_STATE_SET, Color.WHITE); 660 paint.setColor(color); 661 mSelectorWheelPaint = paint; 662 663 // create the animator for showing the input controls 664 mDimSelectorWheelAnimator = ObjectAnimator.ofInt(this, PROPERTY_SELECTOR_PAINT_ALPHA, 665 SELECTOR_WHEEL_BRIGHT_ALPHA, SELECTOR_WHEEL_DIM_ALPHA); 666 final ObjectAnimator showIncrementButton = ObjectAnimator.ofFloat(mIncrementButton, 667 PROPERTY_BUTTON_ALPHA, BUTTON_ALPHA_TRANSPARENT, BUTTON_ALPHA_OPAQUE); 668 final ObjectAnimator showDecrementButton = ObjectAnimator.ofFloat(mDecrementButton, 669 PROPERTY_BUTTON_ALPHA, BUTTON_ALPHA_TRANSPARENT, BUTTON_ALPHA_OPAQUE); 670 mShowInputControlsAnimator = new AnimatorSet(); 671 mShowInputControlsAnimator.playTogether(mDimSelectorWheelAnimator, showIncrementButton, 672 showDecrementButton); 673 mShowInputControlsAnimator.addListener(new AnimatorListenerAdapter() { 674 private boolean mCanceled = false; 675 676 @Override 677 public void onAnimationEnd(Animator animation) { 678 if (!mCanceled) { 679 // if canceled => we still want the wheel drawn 680 setSelectorWheelState(SELECTOR_WHEEL_STATE_SMALL); 681 } 682 mCanceled = false; 683 } 684 685 @Override 686 public void onAnimationCancel(Animator animation) { 687 if (mShowInputControlsAnimator.isRunning()) { 688 mCanceled = true; 689 } 690 } 691 }); 692 693 // create the fling and adjust scrollers 694 mFlingScroller = new Scroller(getContext(), null, true); 695 mAdjustScroller = new Scroller(getContext(), new DecelerateInterpolator(2.5f)); 696 697 updateInputTextView(); 698 updateIncrementAndDecrementButtonsVisibilityState(); 699 700 if (mFlingable) { 701 if (isInEditMode()) { 702 setSelectorWheelState(SELECTOR_WHEEL_STATE_SMALL); 703 } else { 704 // Start with shown selector wheel and hidden controls. When made 705 // visible hide the selector and fade-in the controls to suggest 706 // fling interaction. 707 setSelectorWheelState(SELECTOR_WHEEL_STATE_LARGE); 708 hideInputControls(); 709 } 710 } 711 } 712 713 @Override 714 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 715 final int msrdWdth = getMeasuredWidth(); 716 final int msrdHght = getMeasuredHeight(); 717 718 // Increment button at the top. 719 final int inctBtnMsrdWdth = mIncrementButton.getMeasuredWidth(); 720 final int incrBtnLeft = (msrdWdth - inctBtnMsrdWdth) / 2; 721 final int incrBtnTop = 0; 722 final int incrBtnRight = incrBtnLeft + inctBtnMsrdWdth; 723 final int incrBtnBottom = incrBtnTop + mIncrementButton.getMeasuredHeight(); 724 mIncrementButton.layout(incrBtnLeft, incrBtnTop, incrBtnRight, incrBtnBottom); 725 726 // Input text centered horizontally. 727 final int inptTxtMsrdWdth = mInputText.getMeasuredWidth(); 728 final int inptTxtMsrdHght = mInputText.getMeasuredHeight(); 729 final int inptTxtLeft = (msrdWdth - inptTxtMsrdWdth) / 2; 730 final int inptTxtTop = (msrdHght - inptTxtMsrdHght) / 2; 731 final int inptTxtRight = inptTxtLeft + inptTxtMsrdWdth; 732 final int inptTxtBottom = inptTxtTop + inptTxtMsrdHght; 733 mInputText.layout(inptTxtLeft, inptTxtTop, inptTxtRight, inptTxtBottom); 734 735 // Decrement button at the top. 736 final int decrBtnMsrdWdth = mIncrementButton.getMeasuredWidth(); 737 final int decrBtnLeft = (msrdWdth - decrBtnMsrdWdth) / 2; 738 final int decrBtnTop = msrdHght - mDecrementButton.getMeasuredHeight(); 739 final int decrBtnRight = decrBtnLeft + decrBtnMsrdWdth; 740 final int decrBtnBottom = msrdHght; 741 mDecrementButton.layout(decrBtnLeft, decrBtnTop, decrBtnRight, decrBtnBottom); 742 743 if (!mScrollWheelAndFadingEdgesInitialized) { 744 mScrollWheelAndFadingEdgesInitialized = true; 745 // need to do all this when we know our size 746 initializeSelectorWheel(); 747 initializeFadingEdges(); 748 } 749 } 750 751 @Override 752 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 753 // Try greedily to fit the max width and height. 754 final int newWidthMeasureSpec = makeMeasureSpec(widthMeasureSpec, mMaxWidth); 755 final int newHeightMeasureSpec = makeMeasureSpec(heightMeasureSpec, mMaxHeight); 756 super.onMeasure(newWidthMeasureSpec, newHeightMeasureSpec); 757 // Flag if we are measured with width or height less than the respective min. 758 final int widthSize = resolveSizeAndStateRespectingMinSize(mMinWidth, getMeasuredWidth(), 759 widthMeasureSpec); 760 final int heightSize = resolveSizeAndStateRespectingMinSize(mMinHeight, getMeasuredHeight(), 761 heightMeasureSpec); 762 setMeasuredDimension(widthSize, heightSize); 763 } 764 765 @Override 766 public boolean onInterceptTouchEvent(MotionEvent event) { 767 if (!isEnabled() || !mFlingable) { 768 return false; 769 } 770 switch (event.getActionMasked()) { 771 case MotionEvent.ACTION_DOWN: 772 mLastMotionEventY = mLastDownEventY = event.getY(); 773 removeAllCallbacks(); 774 mShowInputControlsAnimator.cancel(); 775 mDimSelectorWheelAnimator.cancel(); 776 mBeginEditOnUpEvent = false; 777 mAdjustScrollerOnUpEvent = true; 778 if (mSelectorWheelState == SELECTOR_WHEEL_STATE_LARGE) { 779 mSelectorWheelPaint.setAlpha(SELECTOR_WHEEL_BRIGHT_ALPHA); 780 boolean scrollersFinished = mFlingScroller.isFinished() 781 && mAdjustScroller.isFinished(); 782 if (!scrollersFinished) { 783 mFlingScroller.forceFinished(true); 784 mAdjustScroller.forceFinished(true); 785 onScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); 786 } 787 mBeginEditOnUpEvent = scrollersFinished; 788 mAdjustScrollerOnUpEvent = true; 789 hideInputControls(); 790 return true; 791 } 792 if (isEventInVisibleViewHitRect(event, mIncrementButton) 793 || isEventInVisibleViewHitRect(event, mDecrementButton)) { 794 return false; 795 } 796 mAdjustScrollerOnUpEvent = false; 797 setSelectorWheelState(SELECTOR_WHEEL_STATE_LARGE); 798 hideInputControls(); 799 return true; 800 case MotionEvent.ACTION_MOVE: 801 float currentMoveY = event.getY(); 802 int deltaDownY = (int) Math.abs(currentMoveY - mLastDownEventY); 803 if (deltaDownY > mTouchSlop) { 804 mBeginEditOnUpEvent = false; 805 onScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL); 806 setSelectorWheelState(SELECTOR_WHEEL_STATE_LARGE); 807 hideInputControls(); 808 return true; 809 } 810 break; 811 } 812 return false; 813 } 814 815 @Override 816 public boolean onTouchEvent(MotionEvent ev) { 817 if (!isEnabled()) { 818 return false; 819 } 820 if (mVelocityTracker == null) { 821 mVelocityTracker = VelocityTracker.obtain(); 822 } 823 mVelocityTracker.addMovement(ev); 824 int action = ev.getActionMasked(); 825 switch (action) { 826 case MotionEvent.ACTION_MOVE: 827 float currentMoveY = ev.getY(); 828 if (mBeginEditOnUpEvent 829 || mScrollState != OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { 830 int deltaDownY = (int) Math.abs(currentMoveY - mLastDownEventY); 831 if (deltaDownY > mTouchSlop) { 832 mBeginEditOnUpEvent = false; 833 onScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL); 834 } 835 } 836 int deltaMoveY = (int) (currentMoveY - mLastMotionEventY); 837 scrollBy(0, deltaMoveY); 838 invalidate(); 839 mLastMotionEventY = currentMoveY; 840 break; 841 case MotionEvent.ACTION_UP: 842 if (mBeginEditOnUpEvent) { 843 setSelectorWheelState(SELECTOR_WHEEL_STATE_SMALL); 844 showInputControls(mShowInputControlsAnimimationDuration); 845 mInputText.requestFocus(); 846 return true; 847 } 848 VelocityTracker velocityTracker = mVelocityTracker; 849 velocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity); 850 int initialVelocity = (int) velocityTracker.getYVelocity(); 851 if (Math.abs(initialVelocity) > mMinimumFlingVelocity) { 852 fling(initialVelocity); 853 onScrollStateChange(OnScrollListener.SCROLL_STATE_FLING); 854 } else { 855 if (mAdjustScrollerOnUpEvent) { 856 if (mFlingScroller.isFinished() && mAdjustScroller.isFinished()) { 857 postAdjustScrollerCommand(0); 858 } 859 } else { 860 postAdjustScrollerCommand(SHOW_INPUT_CONTROLS_DELAY_MILLIS); 861 } 862 } 863 mVelocityTracker.recycle(); 864 mVelocityTracker = null; 865 break; 866 } 867 return true; 868 } 869 870 @Override 871 public boolean dispatchTouchEvent(MotionEvent event) { 872 final int action = event.getActionMasked(); 873 switch (action) { 874 case MotionEvent.ACTION_MOVE: 875 if (mSelectorWheelState == SELECTOR_WHEEL_STATE_LARGE) { 876 removeAllCallbacks(); 877 forceCompleteChangeCurrentByOneViaScroll(); 878 } 879 break; 880 case MotionEvent.ACTION_CANCEL: 881 case MotionEvent.ACTION_UP: 882 removeAllCallbacks(); 883 break; 884 } 885 return super.dispatchTouchEvent(event); 886 } 887 888 @Override 889 public boolean dispatchKeyEvent(KeyEvent event) { 890 int keyCode = event.getKeyCode(); 891 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) { 892 removeAllCallbacks(); 893 } 894 return super.dispatchKeyEvent(event); 895 } 896 897 @Override 898 public boolean dispatchTrackballEvent(MotionEvent event) { 899 int action = event.getActionMasked(); 900 if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { 901 removeAllCallbacks(); 902 } 903 return super.dispatchTrackballEvent(event); 904 } 905 906 @Override 907 public void computeScroll() { 908 if (mSelectorWheelState == SELECTOR_WHEEL_STATE_NONE) { 909 return; 910 } 911 Scroller scroller = mFlingScroller; 912 if (scroller.isFinished()) { 913 scroller = mAdjustScroller; 914 if (scroller.isFinished()) { 915 return; 916 } 917 } 918 scroller.computeScrollOffset(); 919 int currentScrollerY = scroller.getCurrY(); 920 if (mPreviousScrollerY == 0) { 921 mPreviousScrollerY = scroller.getStartY(); 922 } 923 scrollBy(0, currentScrollerY - mPreviousScrollerY); 924 mPreviousScrollerY = currentScrollerY; 925 if (scroller.isFinished()) { 926 onScrollerFinished(scroller); 927 } else { 928 invalidate(); 929 } 930 } 931 932 @Override 933 public void setEnabled(boolean enabled) { 934 super.setEnabled(enabled); 935 mIncrementButton.setEnabled(enabled); 936 mDecrementButton.setEnabled(enabled); 937 mInputText.setEnabled(enabled); 938 } 939 940 @Override 941 public void scrollBy(int x, int y) { 942 if (mSelectorWheelState == SELECTOR_WHEEL_STATE_NONE) { 943 return; 944 } 945 int[] selectorIndices = mSelectorIndices; 946 if (!mWrapSelectorWheel && y > 0 947 && selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX] <= mMinValue) { 948 mCurrentScrollOffset = mInitialScrollOffset; 949 return; 950 } 951 if (!mWrapSelectorWheel && y < 0 952 && selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX] >= mMaxValue) { 953 mCurrentScrollOffset = mInitialScrollOffset; 954 return; 955 } 956 mCurrentScrollOffset += y; 957 while (mCurrentScrollOffset - mInitialScrollOffset > mSelectorTextGapHeight) { 958 mCurrentScrollOffset -= mSelectorElementHeight; 959 decrementSelectorIndices(selectorIndices); 960 changeCurrent(selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX]); 961 if (!mWrapSelectorWheel && selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX] <= mMinValue) { 962 mCurrentScrollOffset = mInitialScrollOffset; 963 } 964 } 965 while (mCurrentScrollOffset - mInitialScrollOffset < -mSelectorTextGapHeight) { 966 mCurrentScrollOffset += mSelectorElementHeight; 967 incrementSelectorIndices(selectorIndices); 968 changeCurrent(selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX]); 969 if (!mWrapSelectorWheel && selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX] >= mMaxValue) { 970 mCurrentScrollOffset = mInitialScrollOffset; 971 } 972 } 973 } 974 975 @Override 976 public int getSolidColor() { 977 return mSolidColor; 978 } 979 980 /** 981 * Sets the listener to be notified on change of the current value. 982 * 983 * @param onValueChangedListener The listener. 984 */ 985 public void setOnValueChangedListener(OnValueChangeListener onValueChangedListener) { 986 mOnValueChangeListener = onValueChangedListener; 987 } 988 989 /** 990 * Set listener to be notified for scroll state changes. 991 * 992 * @param onScrollListener The listener. 993 */ 994 public void setOnScrollListener(OnScrollListener onScrollListener) { 995 mOnScrollListener = onScrollListener; 996 } 997 998 /** 999 * Set the formatter to be used for formatting the current value. 1000 * <p> 1001 * Note: If you have provided alternative values for the values this 1002 * formatter is never invoked. 1003 * </p> 1004 * 1005 * @param formatter The formatter object. If formatter is <code>null</code>, 1006 * {@link String#valueOf(int)} will be used. 1007 * 1008 * @see #setDisplayedValues(String[]) 1009 */ 1010 public void setFormatter(Formatter formatter) { 1011 if (formatter == mFormatter) { 1012 return; 1013 } 1014 mFormatter = formatter; 1015 initializeSelectorWheelIndices(); 1016 updateInputTextView(); 1017 } 1018 1019 /** 1020 * Set the current value for the number picker. 1021 * <p> 1022 * If the argument is less than the {@link NumberPicker#getMinValue()} and 1023 * {@link NumberPicker#getWrapSelectorWheel()} is <code>false</code> the 1024 * current value is set to the {@link NumberPicker#getMinValue()} value. 1025 * </p> 1026 * <p> 1027 * If the argument is less than the {@link NumberPicker#getMinValue()} and 1028 * {@link NumberPicker#getWrapSelectorWheel()} is <code>true</code> the 1029 * current value is set to the {@link NumberPicker#getMaxValue()} value. 1030 * </p> 1031 * <p> 1032 * If the argument is less than the {@link NumberPicker#getMaxValue()} and 1033 * {@link NumberPicker#getWrapSelectorWheel()} is <code>false</code> the 1034 * current value is set to the {@link NumberPicker#getMaxValue()} value. 1035 * </p> 1036 * <p> 1037 * If the argument is less than the {@link NumberPicker#getMaxValue()} and 1038 * {@link NumberPicker#getWrapSelectorWheel()} is <code>true</code> the 1039 * current value is set to the {@link NumberPicker#getMinValue()} value. 1040 * </p> 1041 * 1042 * @param value The current value. 1043 * @see #setWrapSelectorWheel(boolean) 1044 * @see #setMinValue(int) 1045 * @see #setMaxValue(int) 1046 */ 1047 public void setValue(int value) { 1048 if (mValue == value) { 1049 return; 1050 } 1051 if (value < mMinValue) { 1052 value = mWrapSelectorWheel ? mMaxValue : mMinValue; 1053 } 1054 if (value > mMaxValue) { 1055 value = mWrapSelectorWheel ? mMinValue : mMaxValue; 1056 } 1057 mValue = value; 1058 initializeSelectorWheelIndices(); 1059 updateInputTextView(); 1060 updateIncrementAndDecrementButtonsVisibilityState(); 1061 invalidate(); 1062 } 1063 1064 /** 1065 * Computes the max width if no such specified as an attribute. 1066 */ 1067 private void tryComputeMaxWidth() { 1068 if (!mComputeMaxWidth) { 1069 return; 1070 } 1071 int maxTextWidth = 0; 1072 if (mDisplayedValues == null) { 1073 float maxDigitWidth = 0; 1074 for (int i = 0; i <= 9; i++) { 1075 final float digitWidth = mSelectorWheelPaint.measureText(String.valueOf(i)); 1076 if (digitWidth > maxDigitWidth) { 1077 maxDigitWidth = digitWidth; 1078 } 1079 } 1080 int numberOfDigits = 0; 1081 int current = mMaxValue; 1082 while (current > 0) { 1083 numberOfDigits++; 1084 current = current / 10; 1085 } 1086 maxTextWidth = (int) (numberOfDigits * maxDigitWidth); 1087 } else { 1088 final int valueCount = mDisplayedValues.length; 1089 for (int i = 0; i < valueCount; i++) { 1090 final float textWidth = mSelectorWheelPaint.measureText(mDisplayedValues[i]); 1091 if (textWidth > maxTextWidth) { 1092 maxTextWidth = (int) textWidth; 1093 } 1094 } 1095 } 1096 maxTextWidth += mInputText.getPaddingLeft() + mInputText.getPaddingRight(); 1097 if (mMaxWidth != maxTextWidth) { 1098 if (maxTextWidth > mMinWidth) { 1099 mMaxWidth = maxTextWidth; 1100 } else { 1101 mMaxWidth = mMinWidth; 1102 } 1103 invalidate(); 1104 } 1105 } 1106 1107 /** 1108 * Gets whether the selector wheel wraps when reaching the min/max value. 1109 * 1110 * @return True if the selector wheel wraps. 1111 * 1112 * @see #getMinValue() 1113 * @see #getMaxValue() 1114 */ 1115 public boolean getWrapSelectorWheel() { 1116 return mWrapSelectorWheel; 1117 } 1118 1119 /** 1120 * Sets whether the selector wheel shown during flinging/scrolling should 1121 * wrap around the {@link NumberPicker#getMinValue()} and 1122 * {@link NumberPicker#getMaxValue()} values. 1123 * <p> 1124 * By default if the range (max - min) is more than five (the number of 1125 * items shown on the selector wheel) the selector wheel wrapping is 1126 * enabled. 1127 * </p> 1128 * 1129 * @param wrapSelectorWheel Whether to wrap. 1130 */ 1131 public void setWrapSelectorWheel(boolean wrapSelectorWheel) { 1132 if (wrapSelectorWheel && (mMaxValue - mMinValue) < mSelectorIndices.length) { 1133 throw new IllegalStateException("Range less than selector items count."); 1134 } 1135 if (wrapSelectorWheel != mWrapSelectorWheel) { 1136 mWrapSelectorWheel = wrapSelectorWheel; 1137 updateIncrementAndDecrementButtonsVisibilityState(); 1138 } 1139 } 1140 1141 /** 1142 * Sets the speed at which the numbers be incremented and decremented when 1143 * the up and down buttons are long pressed respectively. 1144 * <p> 1145 * The default value is 300 ms. 1146 * </p> 1147 * 1148 * @param intervalMillis The speed (in milliseconds) at which the numbers 1149 * will be incremented and decremented. 1150 */ 1151 public void setOnLongPressUpdateInterval(long intervalMillis) { 1152 mLongPressUpdateInterval = intervalMillis; 1153 } 1154 1155 /** 1156 * Returns the value of the picker. 1157 * 1158 * @return The value. 1159 */ 1160 public int getValue() { 1161 return mValue; 1162 } 1163 1164 /** 1165 * Returns the min value of the picker. 1166 * 1167 * @return The min value 1168 */ 1169 public int getMinValue() { 1170 return mMinValue; 1171 } 1172 1173 /** 1174 * Sets the min value of the picker. 1175 * 1176 * @param minValue The min value. 1177 */ 1178 public void setMinValue(int minValue) { 1179 if (mMinValue == minValue) { 1180 return; 1181 } 1182 if (minValue < 0) { 1183 throw new IllegalArgumentException("minValue must be >= 0"); 1184 } 1185 mMinValue = minValue; 1186 if (mMinValue > mValue) { 1187 mValue = mMinValue; 1188 } 1189 boolean wrapSelectorWheel = mMaxValue - mMinValue > mSelectorIndices.length; 1190 setWrapSelectorWheel(wrapSelectorWheel); 1191 initializeSelectorWheelIndices(); 1192 updateInputTextView(); 1193 tryComputeMaxWidth(); 1194 } 1195 1196 /** 1197 * Returns the max value of the picker. 1198 * 1199 * @return The max value. 1200 */ 1201 public int getMaxValue() { 1202 return mMaxValue; 1203 } 1204 1205 /** 1206 * Sets the max value of the picker. 1207 * 1208 * @param maxValue The max value. 1209 */ 1210 public void setMaxValue(int maxValue) { 1211 if (mMaxValue == maxValue) { 1212 return; 1213 } 1214 if (maxValue < 0) { 1215 throw new IllegalArgumentException("maxValue must be >= 0"); 1216 } 1217 mMaxValue = maxValue; 1218 if (mMaxValue < mValue) { 1219 mValue = mMaxValue; 1220 } 1221 boolean wrapSelectorWheel = mMaxValue - mMinValue > mSelectorIndices.length; 1222 setWrapSelectorWheel(wrapSelectorWheel); 1223 initializeSelectorWheelIndices(); 1224 updateInputTextView(); 1225 tryComputeMaxWidth(); 1226 } 1227 1228 /** 1229 * Gets the values to be displayed instead of string values. 1230 * 1231 * @return The displayed values. 1232 */ 1233 public String[] getDisplayedValues() { 1234 return mDisplayedValues; 1235 } 1236 1237 /** 1238 * Sets the values to be displayed. 1239 * 1240 * @param displayedValues The displayed values. 1241 */ 1242 public void setDisplayedValues(String[] displayedValues) { 1243 if (mDisplayedValues == displayedValues) { 1244 return; 1245 } 1246 mDisplayedValues = displayedValues; 1247 if (mDisplayedValues != null) { 1248 // Allow text entry rather than strictly numeric entry. 1249 mInputText.setRawInputType(InputType.TYPE_CLASS_TEXT 1250 | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); 1251 } else { 1252 mInputText.setRawInputType(InputType.TYPE_CLASS_NUMBER); 1253 } 1254 updateInputTextView(); 1255 initializeSelectorWheelIndices(); 1256 tryComputeMaxWidth(); 1257 } 1258 1259 @Override 1260 protected float getTopFadingEdgeStrength() { 1261 return TOP_AND_BOTTOM_FADING_EDGE_STRENGTH; 1262 } 1263 1264 @Override 1265 protected float getBottomFadingEdgeStrength() { 1266 return TOP_AND_BOTTOM_FADING_EDGE_STRENGTH; 1267 } 1268 1269 @Override 1270 protected void onAttachedToWindow() { 1271 super.onAttachedToWindow(); 1272 // make sure we show the controls only the very 1273 // first time the user sees this widget 1274 if (mFlingable && !isInEditMode()) { 1275 // animate a bit slower the very first time 1276 showInputControls(mShowInputControlsAnimimationDuration * 2); 1277 } 1278 } 1279 1280 @Override 1281 protected void onDetachedFromWindow() { 1282 removeAllCallbacks(); 1283 } 1284 1285 @Override 1286 protected void dispatchDraw(Canvas canvas) { 1287 // There is a good reason for doing this. See comments in draw(). 1288 } 1289 1290 @Override 1291 public void draw(Canvas canvas) { 1292 // Dispatch draw to our children only if we are not currently running 1293 // the animation for simultaneously dimming the scroll wheel and 1294 // showing in the buttons. This class takes advantage of the View 1295 // implementation of fading edges effect to draw the selector wheel. 1296 // However, in View.draw(), the fading is applied after all the children 1297 // have been drawn and we do not want this fading to be applied to the 1298 // buttons. Therefore, we draw our children after we have completed 1299 // drawing ourselves. 1300 super.draw(canvas); 1301 1302 // Draw our children if we are not showing the selector wheel of fading 1303 // it out 1304 if (mShowInputControlsAnimator.isRunning() 1305 || mSelectorWheelState != SELECTOR_WHEEL_STATE_LARGE) { 1306 long drawTime = getDrawingTime(); 1307 for (int i = 0, count = getChildCount(); i < count; i++) { 1308 View child = getChildAt(i); 1309 if (!child.isShown()) { 1310 continue; 1311 } 1312 drawChild(canvas, getChildAt(i), drawTime); 1313 } 1314 } 1315 } 1316 1317 @Override 1318 protected void onDraw(Canvas canvas) { 1319 if (mSelectorWheelState == SELECTOR_WHEEL_STATE_NONE) { 1320 return; 1321 } 1322 1323 float x = (mRight - mLeft) / 2; 1324 float y = mCurrentScrollOffset; 1325 1326 final int restoreCount = canvas.save(); 1327 1328 if (mSelectorWheelState == SELECTOR_WHEEL_STATE_SMALL) { 1329 Rect clipBounds = canvas.getClipBounds(); 1330 clipBounds.inset(0, mSelectorElementHeight); 1331 canvas.clipRect(clipBounds); 1332 } 1333 1334 // draw the selector wheel 1335 int[] selectorIndices = mSelectorIndices; 1336 for (int i = 0; i < selectorIndices.length; i++) { 1337 int selectorIndex = selectorIndices[i]; 1338 String scrollSelectorValue = mSelectorIndexToStringCache.get(selectorIndex); 1339 // Do not draw the middle item if input is visible since the input is shown only 1340 // if the wheel is static and it covers the middle item. Otherwise, if the user 1341 // starts editing the text via the IME he may see a dimmed version of the old 1342 // value intermixed with the new one. 1343 if (i != SELECTOR_MIDDLE_ITEM_INDEX || mInputText.getVisibility() != VISIBLE) { 1344 canvas.drawText(scrollSelectorValue, x, y, mSelectorWheelPaint); 1345 } 1346 y += mSelectorElementHeight; 1347 } 1348 1349 // draw the selection dividers (only if scrolling and drawable specified) 1350 if (mSelectionDivider != null) { 1351 // draw the top divider 1352 int topOfTopDivider = 1353 (getHeight() - mSelectorElementHeight - mSelectionDividerHeight) / 2; 1354 int bottomOfTopDivider = topOfTopDivider + mSelectionDividerHeight; 1355 mSelectionDivider.setBounds(0, topOfTopDivider, mRight, bottomOfTopDivider); 1356 mSelectionDivider.draw(canvas); 1357 1358 // draw the bottom divider 1359 int topOfBottomDivider = topOfTopDivider + mSelectorElementHeight; 1360 int bottomOfBottomDivider = bottomOfTopDivider + mSelectorElementHeight; 1361 mSelectionDivider.setBounds(0, topOfBottomDivider, mRight, bottomOfBottomDivider); 1362 mSelectionDivider.draw(canvas); 1363 } 1364 1365 canvas.restoreToCount(restoreCount); 1366 } 1367 1368 @Override 1369 public void sendAccessibilityEvent(int eventType) { 1370 // Do not send accessibility events - we want the user to 1371 // perceive this widget as several controls rather as a whole. 1372 } 1373 1374 /** 1375 * Makes a measure spec that tries greedily to use the max value. 1376 * 1377 * @param measureSpec The measure spec. 1378 * @param maxSize The max value for the size. 1379 * @return A measure spec greedily imposing the max size. 1380 */ 1381 private int makeMeasureSpec(int measureSpec, int maxSize) { 1382 if (maxSize == SIZE_UNSPECIFIED) { 1383 return measureSpec; 1384 } 1385 final int size = MeasureSpec.getSize(measureSpec); 1386 final int mode = MeasureSpec.getMode(measureSpec); 1387 switch (mode) { 1388 case MeasureSpec.EXACTLY: 1389 return measureSpec; 1390 case MeasureSpec.AT_MOST: 1391 return MeasureSpec.makeMeasureSpec(Math.min(size, maxSize), MeasureSpec.EXACTLY); 1392 case MeasureSpec.UNSPECIFIED: 1393 return MeasureSpec.makeMeasureSpec(maxSize, MeasureSpec.EXACTLY); 1394 default: 1395 throw new IllegalArgumentException("Unknown measure mode: " + mode); 1396 } 1397 } 1398 1399 /** 1400 * Utility to reconcile a desired size and state, with constraints imposed by 1401 * a MeasureSpec. Tries to respect the min size, unless a different size is 1402 * imposed by the constraints. 1403 * 1404 * @param minSize The minimal desired size. 1405 * @param measuredSize The currently measured size. 1406 * @param measureSpec The current measure spec. 1407 * @return The resolved size and state. 1408 */ 1409 private int resolveSizeAndStateRespectingMinSize(int minSize, int measuredSize, 1410 int measureSpec) { 1411 if (minSize != SIZE_UNSPECIFIED) { 1412 final int desiredWidth = Math.max(minSize, measuredSize); 1413 return resolveSizeAndState(desiredWidth, measureSpec, 0); 1414 } else { 1415 return measuredSize; 1416 } 1417 } 1418 1419 /** 1420 * Resets the selector indices and clear the cached 1421 * string representation of these indices. 1422 */ 1423 private void initializeSelectorWheelIndices() { 1424 mSelectorIndexToStringCache.clear(); 1425 int[] selectorIdices = mSelectorIndices; 1426 int current = getValue(); 1427 for (int i = 0; i < mSelectorIndices.length; i++) { 1428 int selectorIndex = current + (i - SELECTOR_MIDDLE_ITEM_INDEX); 1429 if (mWrapSelectorWheel) { 1430 selectorIndex = getWrappedSelectorIndex(selectorIndex); 1431 } 1432 mSelectorIndices[i] = selectorIndex; 1433 ensureCachedScrollSelectorValue(mSelectorIndices[i]); 1434 } 1435 } 1436 1437 /** 1438 * Sets the current value of this NumberPicker, and sets mPrevious to the 1439 * previous value. If current is greater than mEnd less than mStart, the 1440 * value of mCurrent is wrapped around. Subclasses can override this to 1441 * change the wrapping behavior 1442 * 1443 * @param current the new value of the NumberPicker 1444 */ 1445 private void changeCurrent(int current) { 1446 if (mValue == current) { 1447 return; 1448 } 1449 // Wrap around the values if we go past the start or end 1450 if (mWrapSelectorWheel) { 1451 current = getWrappedSelectorIndex(current); 1452 } 1453 int previous = mValue; 1454 setValue(current); 1455 notifyChange(previous, current); 1456 } 1457 1458 /** 1459 * Changes the current value by one which is increment or 1460 * decrement based on the passes argument. 1461 * 1462 * @param increment True to increment, false to decrement. 1463 */ 1464 private void changeCurrentByOne(boolean increment) { 1465 if (mFlingable) { 1466 mDimSelectorWheelAnimator.cancel(); 1467 mInputText.setVisibility(View.INVISIBLE); 1468 mSelectorWheelPaint.setAlpha(SELECTOR_WHEEL_BRIGHT_ALPHA); 1469 mPreviousScrollerY = 0; 1470 forceCompleteChangeCurrentByOneViaScroll(); 1471 if (increment) { 1472 mFlingScroller.startScroll(0, 0, 0, -mSelectorElementHeight, 1473 CHANGE_CURRENT_BY_ONE_SCROLL_DURATION); 1474 } else { 1475 mFlingScroller.startScroll(0, 0, 0, mSelectorElementHeight, 1476 CHANGE_CURRENT_BY_ONE_SCROLL_DURATION); 1477 } 1478 invalidate(); 1479 } else { 1480 if (increment) { 1481 changeCurrent(mValue + 1); 1482 } else { 1483 changeCurrent(mValue - 1); 1484 } 1485 } 1486 } 1487 1488 /** 1489 * Ensures that if we are in the process of changing the current value 1490 * by one via scrolling the scroller gets to its final state and the 1491 * value is updated. 1492 */ 1493 private void forceCompleteChangeCurrentByOneViaScroll() { 1494 Scroller scroller = mFlingScroller; 1495 if (!scroller.isFinished()) { 1496 final int yBeforeAbort = scroller.getCurrY(); 1497 scroller.abortAnimation(); 1498 final int yDelta = scroller.getCurrY() - yBeforeAbort; 1499 scrollBy(0, yDelta); 1500 } 1501 } 1502 1503 /** 1504 * Sets the <code>alpha</code> of the {@link Paint} for drawing the selector 1505 * wheel. 1506 */ 1507 @SuppressWarnings("unused") 1508 // Called via reflection 1509 private void setSelectorPaintAlpha(int alpha) { 1510 mSelectorWheelPaint.setAlpha(alpha); 1511 invalidate(); 1512 } 1513 1514 /** 1515 * @return If the <code>event</code> is in the visible <code>view</code>. 1516 */ 1517 private boolean isEventInVisibleViewHitRect(MotionEvent event, View view) { 1518 if (view.getVisibility() == VISIBLE) { 1519 view.getHitRect(mTempRect); 1520 return mTempRect.contains((int) event.getX(), (int) event.getY()); 1521 } 1522 return false; 1523 } 1524 1525 /** 1526 * Sets the <code>selectorWheelState</code>. 1527 */ 1528 private void setSelectorWheelState(int selectorWheelState) { 1529 mSelectorWheelState = selectorWheelState; 1530 if (selectorWheelState == SELECTOR_WHEEL_STATE_LARGE) { 1531 mSelectorWheelPaint.setAlpha(SELECTOR_WHEEL_BRIGHT_ALPHA); 1532 } 1533 1534 if (mFlingable && selectorWheelState == SELECTOR_WHEEL_STATE_LARGE 1535 && AccessibilityManager.getInstance(mContext).isEnabled()) { 1536 AccessibilityManager.getInstance(mContext).interrupt(); 1537 String text = mContext.getString(R.string.number_picker_increment_scroll_action); 1538 mInputText.setContentDescription(text); 1539 mInputText.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 1540 mInputText.setContentDescription(null); 1541 } 1542 } 1543 1544 private void initializeSelectorWheel() { 1545 initializeSelectorWheelIndices(); 1546 int[] selectorIndices = mSelectorIndices; 1547 int totalTextHeight = selectorIndices.length * mTextSize; 1548 float totalTextGapHeight = (mBottom - mTop) - totalTextHeight; 1549 float textGapCount = selectorIndices.length - 1; 1550 mSelectorTextGapHeight = (int) (totalTextGapHeight / textGapCount + 0.5f); 1551 mSelectorElementHeight = mTextSize + mSelectorTextGapHeight; 1552 // Ensure that the middle item is positioned the same as the text in mInputText 1553 int editTextTextPosition = mInputText.getBaseline() + mInputText.getTop(); 1554 mInitialScrollOffset = editTextTextPosition - 1555 (mSelectorElementHeight * SELECTOR_MIDDLE_ITEM_INDEX); 1556 mCurrentScrollOffset = mInitialScrollOffset; 1557 updateInputTextView(); 1558 } 1559 1560 private void initializeFadingEdges() { 1561 setVerticalFadingEdgeEnabled(true); 1562 setFadingEdgeLength((mBottom - mTop - mTextSize) / 2); 1563 } 1564 1565 /** 1566 * Callback invoked upon completion of a given <code>scroller</code>. 1567 */ 1568 private void onScrollerFinished(Scroller scroller) { 1569 if (scroller == mFlingScroller) { 1570 if (mSelectorWheelState == SELECTOR_WHEEL_STATE_LARGE) { 1571 postAdjustScrollerCommand(0); 1572 onScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); 1573 } else { 1574 updateInputTextView(); 1575 fadeSelectorWheel(mShowInputControlsAnimimationDuration); 1576 } 1577 } else { 1578 updateInputTextView(); 1579 showInputControls(mShowInputControlsAnimimationDuration); 1580 } 1581 } 1582 1583 /** 1584 * Handles transition to a given <code>scrollState</code> 1585 */ 1586 private void onScrollStateChange(int scrollState) { 1587 if (mScrollState == scrollState) { 1588 return; 1589 } 1590 mScrollState = scrollState; 1591 if (mOnScrollListener != null) { 1592 mOnScrollListener.onScrollStateChange(this, scrollState); 1593 } 1594 } 1595 1596 /** 1597 * Flings the selector with the given <code>velocityY</code>. 1598 */ 1599 private void fling(int velocityY) { 1600 mPreviousScrollerY = 0; 1601 1602 if (velocityY > 0) { 1603 mFlingScroller.fling(0, 0, 0, velocityY, 0, 0, 0, Integer.MAX_VALUE); 1604 } else { 1605 mFlingScroller.fling(0, Integer.MAX_VALUE, 0, velocityY, 0, 0, 0, Integer.MAX_VALUE); 1606 } 1607 1608 invalidate(); 1609 } 1610 1611 /** 1612 * Hides the input controls which is the up/down arrows and the text field. 1613 */ 1614 private void hideInputControls() { 1615 mShowInputControlsAnimator.cancel(); 1616 mIncrementButton.setVisibility(INVISIBLE); 1617 mDecrementButton.setVisibility(INVISIBLE); 1618 mInputText.setVisibility(INVISIBLE); 1619 } 1620 1621 /** 1622 * Show the input controls by making them visible and animating the alpha 1623 * property up/down arrows. 1624 * 1625 * @param animationDuration The duration of the animation. 1626 */ 1627 private void showInputControls(long animationDuration) { 1628 updateIncrementAndDecrementButtonsVisibilityState(); 1629 mInputText.setVisibility(VISIBLE); 1630 mShowInputControlsAnimator.setDuration(animationDuration); 1631 mShowInputControlsAnimator.start(); 1632 } 1633 1634 /** 1635 * Fade the selector wheel via an animation. 1636 * 1637 * @param animationDuration The duration of the animation. 1638 */ 1639 private void fadeSelectorWheel(long animationDuration) { 1640 mInputText.setVisibility(VISIBLE); 1641 mDimSelectorWheelAnimator.setDuration(animationDuration); 1642 mDimSelectorWheelAnimator.start(); 1643 } 1644 1645 /** 1646 * Updates the visibility state of the increment and decrement buttons. 1647 */ 1648 private void updateIncrementAndDecrementButtonsVisibilityState() { 1649 if (mWrapSelectorWheel || mValue < mMaxValue) { 1650 mIncrementButton.setVisibility(VISIBLE); 1651 } else { 1652 mIncrementButton.setVisibility(INVISIBLE); 1653 } 1654 if (mWrapSelectorWheel || mValue > mMinValue) { 1655 mDecrementButton.setVisibility(VISIBLE); 1656 } else { 1657 mDecrementButton.setVisibility(INVISIBLE); 1658 } 1659 } 1660 1661 /** 1662 * @return The wrapped index <code>selectorIndex</code> value. 1663 */ 1664 private int getWrappedSelectorIndex(int selectorIndex) { 1665 if (selectorIndex > mMaxValue) { 1666 return mMinValue + (selectorIndex - mMaxValue) % (mMaxValue - mMinValue) - 1; 1667 } else if (selectorIndex < mMinValue) { 1668 return mMaxValue - (mMinValue - selectorIndex) % (mMaxValue - mMinValue) + 1; 1669 } 1670 return selectorIndex; 1671 } 1672 1673 /** 1674 * Increments the <code>selectorIndices</code> whose string representations 1675 * will be displayed in the selector. 1676 */ 1677 private void incrementSelectorIndices(int[] selectorIndices) { 1678 for (int i = 0; i < selectorIndices.length - 1; i++) { 1679 selectorIndices[i] = selectorIndices[i + 1]; 1680 } 1681 int nextScrollSelectorIndex = selectorIndices[selectorIndices.length - 2] + 1; 1682 if (mWrapSelectorWheel && nextScrollSelectorIndex > mMaxValue) { 1683 nextScrollSelectorIndex = mMinValue; 1684 } 1685 selectorIndices[selectorIndices.length - 1] = nextScrollSelectorIndex; 1686 ensureCachedScrollSelectorValue(nextScrollSelectorIndex); 1687 } 1688 1689 /** 1690 * Decrements the <code>selectorIndices</code> whose string representations 1691 * will be displayed in the selector. 1692 */ 1693 private void decrementSelectorIndices(int[] selectorIndices) { 1694 for (int i = selectorIndices.length - 1; i > 0; i--) { 1695 selectorIndices[i] = selectorIndices[i - 1]; 1696 } 1697 int nextScrollSelectorIndex = selectorIndices[1] - 1; 1698 if (mWrapSelectorWheel && nextScrollSelectorIndex < mMinValue) { 1699 nextScrollSelectorIndex = mMaxValue; 1700 } 1701 selectorIndices[0] = nextScrollSelectorIndex; 1702 ensureCachedScrollSelectorValue(nextScrollSelectorIndex); 1703 } 1704 1705 /** 1706 * Ensures we have a cached string representation of the given <code> 1707 * selectorIndex</code> 1708 * to avoid multiple instantiations of the same string. 1709 */ 1710 private void ensureCachedScrollSelectorValue(int selectorIndex) { 1711 SparseArray<String> cache = mSelectorIndexToStringCache; 1712 String scrollSelectorValue = cache.get(selectorIndex); 1713 if (scrollSelectorValue != null) { 1714 return; 1715 } 1716 if (selectorIndex < mMinValue || selectorIndex > mMaxValue) { 1717 scrollSelectorValue = ""; 1718 } else { 1719 if (mDisplayedValues != null) { 1720 int displayedValueIndex = selectorIndex - mMinValue; 1721 scrollSelectorValue = mDisplayedValues[displayedValueIndex]; 1722 } else { 1723 scrollSelectorValue = formatNumber(selectorIndex); 1724 } 1725 } 1726 cache.put(selectorIndex, scrollSelectorValue); 1727 } 1728 1729 private String formatNumber(int value) { 1730 return (mFormatter != null) ? mFormatter.format(value) : String.valueOf(value); 1731 } 1732 1733 private void validateInputTextView(View v) { 1734 String str = String.valueOf(((TextView) v).getText()); 1735 if (TextUtils.isEmpty(str)) { 1736 // Restore to the old value as we don't allow empty values 1737 updateInputTextView(); 1738 } else { 1739 // Check the new value and ensure it's in range 1740 int current = getSelectedPos(str.toString()); 1741 changeCurrent(current); 1742 } 1743 } 1744 1745 /** 1746 * Updates the view of this NumberPicker. If displayValues were specified in 1747 * the string corresponding to the index specified by the current value will 1748 * be returned. Otherwise, the formatter specified in {@link #setFormatter} 1749 * will be used to format the number. 1750 */ 1751 private void updateInputTextView() { 1752 /* 1753 * If we don't have displayed values then use the current number else 1754 * find the correct value in the displayed values for the current 1755 * number. 1756 */ 1757 if (mDisplayedValues == null) { 1758 mInputText.setText(formatNumber(mValue)); 1759 } else { 1760 mInputText.setText(mDisplayedValues[mValue - mMinValue]); 1761 } 1762 mInputText.setSelection(mInputText.getText().length()); 1763 1764 if (mFlingable && AccessibilityManager.getInstance(mContext).isEnabled()) { 1765 String text = mContext.getString(R.string.number_picker_increment_scroll_mode, 1766 mInputText.getText()); 1767 mInputText.setContentDescription(text); 1768 } 1769 } 1770 1771 /** 1772 * Notifies the listener, if registered, of a change of the value of this 1773 * NumberPicker. 1774 */ 1775 private void notifyChange(int previous, int current) { 1776 if (mOnValueChangeListener != null) { 1777 mOnValueChangeListener.onValueChange(this, previous, mValue); 1778 } 1779 } 1780 1781 /** 1782 * Posts a command for changing the current value by one. 1783 * 1784 * @param increment Whether to increment or decrement the value. 1785 */ 1786 private void postChangeCurrentByOneFromLongPress(boolean increment) { 1787 mInputText.clearFocus(); 1788 removeAllCallbacks(); 1789 if (mChangeCurrentByOneFromLongPressCommand == null) { 1790 mChangeCurrentByOneFromLongPressCommand = new ChangeCurrentByOneFromLongPressCommand(); 1791 } 1792 mChangeCurrentByOneFromLongPressCommand.setIncrement(increment); 1793 post(mChangeCurrentByOneFromLongPressCommand); 1794 } 1795 1796 /** 1797 * Removes all pending callback from the message queue. 1798 */ 1799 private void removeAllCallbacks() { 1800 if (mChangeCurrentByOneFromLongPressCommand != null) { 1801 removeCallbacks(mChangeCurrentByOneFromLongPressCommand); 1802 } 1803 if (mAdjustScrollerCommand != null) { 1804 removeCallbacks(mAdjustScrollerCommand); 1805 } 1806 if (mSetSelectionCommand != null) { 1807 removeCallbacks(mSetSelectionCommand); 1808 } 1809 } 1810 1811 /** 1812 * @return The selected index given its displayed <code>value</code>. 1813 */ 1814 private int getSelectedPos(String value) { 1815 if (mDisplayedValues == null) { 1816 try { 1817 return Integer.parseInt(value); 1818 } catch (NumberFormatException e) { 1819 // Ignore as if it's not a number we don't care 1820 } 1821 } else { 1822 for (int i = 0; i < mDisplayedValues.length; i++) { 1823 // Don't force the user to type in jan when ja will do 1824 value = value.toLowerCase(); 1825 if (mDisplayedValues[i].toLowerCase().startsWith(value)) { 1826 return mMinValue + i; 1827 } 1828 } 1829 1830 /* 1831 * The user might have typed in a number into the month field i.e. 1832 * 10 instead of OCT so support that too. 1833 */ 1834 try { 1835 return Integer.parseInt(value); 1836 } catch (NumberFormatException e) { 1837 1838 // Ignore as if it's not a number we don't care 1839 } 1840 } 1841 return mMinValue; 1842 } 1843 1844 /** 1845 * Posts an {@link SetSelectionCommand} from the given <code>selectionStart 1846 * </code> to 1847 * <code>selectionEnd</code>. 1848 */ 1849 private void postSetSelectionCommand(int selectionStart, int selectionEnd) { 1850 if (mSetSelectionCommand == null) { 1851 mSetSelectionCommand = new SetSelectionCommand(); 1852 } else { 1853 removeCallbacks(mSetSelectionCommand); 1854 } 1855 mSetSelectionCommand.mSelectionStart = selectionStart; 1856 mSetSelectionCommand.mSelectionEnd = selectionEnd; 1857 post(mSetSelectionCommand); 1858 } 1859 1860 /** 1861 * Posts an {@link AdjustScrollerCommand} within the given <code> 1862 * delayMillis</code> 1863 * . 1864 */ 1865 private void postAdjustScrollerCommand(int delayMillis) { 1866 if (mAdjustScrollerCommand == null) { 1867 mAdjustScrollerCommand = new AdjustScrollerCommand(); 1868 } else { 1869 removeCallbacks(mAdjustScrollerCommand); 1870 } 1871 postDelayed(mAdjustScrollerCommand, delayMillis); 1872 } 1873 1874 /** 1875 * Filter for accepting only valid indices or prefixes of the string 1876 * representation of valid indices. 1877 */ 1878 class InputTextFilter extends NumberKeyListener { 1879 1880 // XXX This doesn't allow for range limits when controlled by a 1881 // soft input method! 1882 public int getInputType() { 1883 return InputType.TYPE_CLASS_TEXT; 1884 } 1885 1886 @Override 1887 protected char[] getAcceptedChars() { 1888 return DIGIT_CHARACTERS; 1889 } 1890 1891 @Override 1892 public CharSequence filter(CharSequence source, int start, int end, Spanned dest, 1893 int dstart, int dend) { 1894 if (mDisplayedValues == null) { 1895 CharSequence filtered = super.filter(source, start, end, dest, dstart, dend); 1896 if (filtered == null) { 1897 filtered = source.subSequence(start, end); 1898 } 1899 1900 String result = String.valueOf(dest.subSequence(0, dstart)) + filtered 1901 + dest.subSequence(dend, dest.length()); 1902 1903 if ("".equals(result)) { 1904 return result; 1905 } 1906 int val = getSelectedPos(result); 1907 1908 /* 1909 * Ensure the user can't type in a value greater than the max 1910 * allowed. We have to allow less than min as the user might 1911 * want to delete some numbers and then type a new number. 1912 */ 1913 if (val > mMaxValue) { 1914 return ""; 1915 } else { 1916 return filtered; 1917 } 1918 } else { 1919 CharSequence filtered = String.valueOf(source.subSequence(start, end)); 1920 if (TextUtils.isEmpty(filtered)) { 1921 return ""; 1922 } 1923 String result = String.valueOf(dest.subSequence(0, dstart)) + filtered 1924 + dest.subSequence(dend, dest.length()); 1925 String str = String.valueOf(result).toLowerCase(); 1926 for (String val : mDisplayedValues) { 1927 String valLowerCase = val.toLowerCase(); 1928 if (valLowerCase.startsWith(str)) { 1929 postSetSelectionCommand(result.length(), val.length()); 1930 return val.subSequence(dstart, val.length()); 1931 } 1932 } 1933 return ""; 1934 } 1935 } 1936 } 1937 1938 /** 1939 * Command for setting the input text selection. 1940 */ 1941 class SetSelectionCommand implements Runnable { 1942 private int mSelectionStart; 1943 1944 private int mSelectionEnd; 1945 1946 public void run() { 1947 mInputText.setSelection(mSelectionStart, mSelectionEnd); 1948 } 1949 } 1950 1951 /** 1952 * Command for adjusting the scroller to show in its center the closest of 1953 * the displayed items. 1954 */ 1955 class AdjustScrollerCommand implements Runnable { 1956 public void run() { 1957 mPreviousScrollerY = 0; 1958 if (mInitialScrollOffset == mCurrentScrollOffset) { 1959 updateInputTextView(); 1960 showInputControls(mShowInputControlsAnimimationDuration); 1961 return; 1962 } 1963 // adjust to the closest value 1964 int deltaY = mInitialScrollOffset - mCurrentScrollOffset; 1965 if (Math.abs(deltaY) > mSelectorElementHeight / 2) { 1966 deltaY += (deltaY > 0) ? -mSelectorElementHeight : mSelectorElementHeight; 1967 } 1968 mAdjustScroller.startScroll(0, 0, 0, deltaY, SELECTOR_ADJUSTMENT_DURATION_MILLIS); 1969 invalidate(); 1970 } 1971 } 1972 1973 /** 1974 * Command for changing the current value from a long press by one. 1975 */ 1976 class ChangeCurrentByOneFromLongPressCommand implements Runnable { 1977 private boolean mIncrement; 1978 1979 private void setIncrement(boolean increment) { 1980 mIncrement = increment; 1981 } 1982 1983 public void run() { 1984 changeCurrentByOne(mIncrement); 1985 postDelayed(this, mLongPressUpdateInterval); 1986 } 1987 } 1988} 1989