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