NumberPicker.java revision d11e6151fe88314505fa7adca6278de2e772b11c
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 changing the 116 * current value by one, i.e. increment or decrement. 117 */ 118 private static final int CHANGE_CURRENT_BY_ONE_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.5f; 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 == Integer.MAX_VALUE); 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 if (!mFlingScroller.isFinished()) { 775 mFlingScroller.forceFinished(true); 776 mAdjustScroller.forceFinished(true); 777 onScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); 778 } else if (!mAdjustScroller.isFinished()) { 779 mFlingScroller.forceFinished(true); 780 mAdjustScroller.forceFinished(true); 781 } else if (mLastDownEventY < mTopSelectionDividerTop) { 782 hideSoftInput(); 783 postChangeCurrentByOneFromLongPress( 784 false, ViewConfiguration.getLongPressTimeout()); 785 } else if (mLastDownEventY > mBottomSelectionDividerBottom) { 786 hideSoftInput(); 787 postChangeCurrentByOneFromLongPress( 788 true, ViewConfiguration.getLongPressTimeout()); 789 } else { 790 mShowSoftInputOnTap = true; 791 postBeginSoftInputOnLongPressCommand(); 792 } 793 return true; 794 } 795 } 796 return false; 797 } 798 799 @Override 800 public boolean onTouchEvent(MotionEvent event) { 801 if (!isEnabled() || !mHasSelectorWheel) { 802 return false; 803 } 804 if (mVelocityTracker == null) { 805 mVelocityTracker = VelocityTracker.obtain(); 806 } 807 mVelocityTracker.addMovement(event); 808 int action = event.getActionMasked(); 809 switch (action) { 810 case MotionEvent.ACTION_MOVE: { 811 if (mIngonreMoveEvents) { 812 break; 813 } 814 float currentMoveY = event.getY(); 815 if (mScrollState != OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { 816 int deltaDownY = (int) Math.abs(currentMoveY - mLastDownEventY); 817 if (deltaDownY > mTouchSlop) { 818 removeAllCallbacks(); 819 onScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL); 820 } 821 } else { 822 int deltaMoveY = (int) ((currentMoveY - mLastDownOrMoveEventY) 823 / TOUCH_SCROLL_DECELERATION_COEFFICIENT); 824 scrollBy(0, deltaMoveY); 825 invalidate(); 826 } 827 mLastDownOrMoveEventY = currentMoveY; 828 } break; 829 case MotionEvent.ACTION_UP: { 830 removeBeginSoftInputCommand(); 831 removeChangeCurrentByOneFromLongPress(); 832 VelocityTracker velocityTracker = mVelocityTracker; 833 velocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity); 834 int initialVelocity = (int) velocityTracker.getYVelocity(); 835 if (Math.abs(initialVelocity) > mMinimumFlingVelocity) { 836 int deltaMove = (int) (event.getY() - mLastDownEventY); 837 int absDeltaMoveY = Math.abs(deltaMove); 838 if (absDeltaMoveY > mMinFlingDistance) { 839 fling(initialVelocity); 840 } else { 841 changeValueByOne(deltaMove < 0); 842 } 843 onScrollStateChange(OnScrollListener.SCROLL_STATE_FLING); 844 } else { 845 int eventY = (int) event.getY(); 846 int deltaMoveY = (int) Math.abs(eventY - mLastDownEventY); 847 long deltaTime = event.getEventTime() - mLastDownEventTime; 848 if (deltaMoveY <= mTouchSlop && deltaTime < ViewConfiguration.getTapTimeout()) { 849 if (mShowSoftInputOnTap) { 850 mShowSoftInputOnTap = false; 851 showSoftInput(); 852 } else { 853 int selectorIndexOffset = (eventY / mSelectorElementHeight) 854 - SELECTOR_MIDDLE_ITEM_INDEX; 855 if (selectorIndexOffset > 0) { 856 changeValueByOne(true); 857 } else if (selectorIndexOffset < 0) { 858 changeValueByOne(false); 859 } 860 } 861 } else { 862 ensureScrollWheelAdjusted(); 863 } 864 onScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); 865 } 866 mVelocityTracker.recycle(); 867 mVelocityTracker = null; 868 } break; 869 } 870 return true; 871 } 872 873 @Override 874 public boolean dispatchTouchEvent(MotionEvent event) { 875 final int action = event.getActionMasked(); 876 switch (action) { 877 case MotionEvent.ACTION_CANCEL: 878 case MotionEvent.ACTION_UP: 879 removeAllCallbacks(); 880 break; 881 } 882 return super.dispatchTouchEvent(event); 883 } 884 885 @Override 886 public boolean dispatchKeyEvent(KeyEvent event) { 887 final int keyCode = event.getKeyCode(); 888 switch (keyCode) { 889 case KeyEvent.KEYCODE_DPAD_CENTER: 890 case KeyEvent.KEYCODE_ENTER: 891 removeAllCallbacks(); 892 break; 893 } 894 return super.dispatchKeyEvent(event); 895 } 896 897 @Override 898 public boolean dispatchTrackballEvent(MotionEvent event) { 899 final int action = event.getActionMasked(); 900 switch (action) { 901 case MotionEvent.ACTION_CANCEL: 902 case MotionEvent.ACTION_UP: 903 removeAllCallbacks(); 904 break; 905 } 906 return super.dispatchTrackballEvent(event); 907 } 908 909 @Override 910 protected boolean dispatchHoverEvent(MotionEvent event) { 911 if (!mHasSelectorWheel) { 912 return super.dispatchHoverEvent(event); 913 } 914 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 915 final int eventY = (int) event.getY(); 916 final int hoveredVirtualViewId; 917 if (eventY < mTopSelectionDividerTop) { 918 hoveredVirtualViewId = AccessibilityNodeProviderImpl.VIRTUAL_VIEW_ID_DECREMENT; 919 } else if (eventY > mBottomSelectionDividerBottom) { 920 hoveredVirtualViewId = AccessibilityNodeProviderImpl.VIRTUAL_VIEW_ID_INCREMENT; 921 } else { 922 hoveredVirtualViewId = AccessibilityNodeProviderImpl.VIRTUAL_VIEW_ID_INPUT; 923 } 924 final int action = event.getActionMasked(); 925 AccessibilityNodeProviderImpl provider = 926 (AccessibilityNodeProviderImpl) getAccessibilityNodeProvider(); 927 switch (action) { 928 case MotionEvent.ACTION_HOVER_ENTER: { 929 provider.sendAccessibilityEventForVirtualView(hoveredVirtualViewId, 930 AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 931 mLastHoveredChildVirtualViewId = hoveredVirtualViewId; 932 } break; 933 case MotionEvent.ACTION_HOVER_MOVE: { 934 if (mLastHoveredChildVirtualViewId != hoveredVirtualViewId 935 && mLastHoveredChildVirtualViewId != View.NO_ID) { 936 provider.sendAccessibilityEventForVirtualView( 937 mLastHoveredChildVirtualViewId, 938 AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 939 provider.sendAccessibilityEventForVirtualView(hoveredVirtualViewId, 940 AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 941 mLastHoveredChildVirtualViewId = hoveredVirtualViewId; 942 } 943 } break; 944 case MotionEvent.ACTION_HOVER_EXIT: { 945 provider.sendAccessibilityEventForVirtualView(hoveredVirtualViewId, 946 AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 947 mLastHoveredChildVirtualViewId = View.NO_ID; 948 } break; 949 } 950 } 951 return false; 952 } 953 954 @Override 955 public void computeScroll() { 956 Scroller scroller = mFlingScroller; 957 if (scroller.isFinished()) { 958 scroller = mAdjustScroller; 959 if (scroller.isFinished()) { 960 return; 961 } 962 } 963 scroller.computeScrollOffset(); 964 int currentScrollerY = scroller.getCurrY(); 965 if (mPreviousScrollerY == 0) { 966 mPreviousScrollerY = scroller.getStartY(); 967 } 968 scrollBy(0, currentScrollerY - mPreviousScrollerY); 969 mPreviousScrollerY = currentScrollerY; 970 if (scroller.isFinished()) { 971 onScrollerFinished(scroller); 972 } else { 973 invalidate(); 974 } 975 } 976 977 @Override 978 public void setEnabled(boolean enabled) { 979 super.setEnabled(enabled); 980 if (!mHasSelectorWheel) { 981 mIncrementButton.setEnabled(enabled); 982 } 983 if (!mHasSelectorWheel) { 984 mDecrementButton.setEnabled(enabled); 985 } 986 mInputText.setEnabled(enabled); 987 } 988 989 @Override 990 public void scrollBy(int x, int y) { 991 int[] selectorIndices = mSelectorIndices; 992 if (!mWrapSelectorWheel && y > 0 993 && selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX] <= mMinValue) { 994 mCurrentScrollOffset = mInitialScrollOffset; 995 return; 996 } 997 if (!mWrapSelectorWheel && y < 0 998 && selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX] >= mMaxValue) { 999 mCurrentScrollOffset = mInitialScrollOffset; 1000 return; 1001 } 1002 mCurrentScrollOffset += y; 1003 while (mCurrentScrollOffset - mInitialScrollOffset > mSelectorTextGapHeight) { 1004 mCurrentScrollOffset -= mSelectorElementHeight; 1005 decrementSelectorIndices(selectorIndices); 1006 setValueInternal(selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX], true); 1007 if (!mWrapSelectorWheel && selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX] <= mMinValue) { 1008 mCurrentScrollOffset = mInitialScrollOffset; 1009 } 1010 } 1011 while (mCurrentScrollOffset - mInitialScrollOffset < -mSelectorTextGapHeight) { 1012 mCurrentScrollOffset += mSelectorElementHeight; 1013 incrementSelectorIndices(selectorIndices); 1014 setValueInternal(selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX], true); 1015 if (!mWrapSelectorWheel && selectorIndices[SELECTOR_MIDDLE_ITEM_INDEX] >= mMaxValue) { 1016 mCurrentScrollOffset = mInitialScrollOffset; 1017 } 1018 } 1019 } 1020 1021 @Override 1022 public int getSolidColor() { 1023 return mSolidColor; 1024 } 1025 1026 /** 1027 * Sets the listener to be notified on change of the current value. 1028 * 1029 * @param onValueChangedListener The listener. 1030 */ 1031 public void setOnValueChangedListener(OnValueChangeListener onValueChangedListener) { 1032 mOnValueChangeListener = onValueChangedListener; 1033 } 1034 1035 /** 1036 * Set listener to be notified for scroll state changes. 1037 * 1038 * @param onScrollListener The listener. 1039 */ 1040 public void setOnScrollListener(OnScrollListener onScrollListener) { 1041 mOnScrollListener = onScrollListener; 1042 } 1043 1044 /** 1045 * Set the formatter to be used for formatting the current value. 1046 * <p> 1047 * Note: If you have provided alternative values for the values this 1048 * formatter is never invoked. 1049 * </p> 1050 * 1051 * @param formatter The formatter object. If formatter is <code>null</code>, 1052 * {@link String#valueOf(int)} will be used. 1053 *@see #setDisplayedValues(String[]) 1054 */ 1055 public void setFormatter(Formatter formatter) { 1056 if (formatter == mFormatter) { 1057 return; 1058 } 1059 mFormatter = formatter; 1060 initializeSelectorWheelIndices(); 1061 updateInputTextView(); 1062 } 1063 1064 /** 1065 * Set the current value for the number picker. 1066 * <p> 1067 * If the argument is less than the {@link NumberPicker#getMinValue()} and 1068 * {@link NumberPicker#getWrapSelectorWheel()} is <code>false</code> the 1069 * current value is set to the {@link NumberPicker#getMinValue()} value. 1070 * </p> 1071 * <p> 1072 * If the argument is less than the {@link NumberPicker#getMinValue()} and 1073 * {@link NumberPicker#getWrapSelectorWheel()} is <code>true</code> the 1074 * current value is set to the {@link NumberPicker#getMaxValue()} value. 1075 * </p> 1076 * <p> 1077 * If the argument is less than the {@link NumberPicker#getMaxValue()} and 1078 * {@link NumberPicker#getWrapSelectorWheel()} is <code>false</code> the 1079 * current value is set to the {@link NumberPicker#getMaxValue()} value. 1080 * </p> 1081 * <p> 1082 * If the argument is less than the {@link NumberPicker#getMaxValue()} and 1083 * {@link NumberPicker#getWrapSelectorWheel()} is <code>true</code> the 1084 * current value is set to the {@link NumberPicker#getMinValue()} value. 1085 * </p> 1086 * 1087 * @param value The current value. 1088 * @see #setWrapSelectorWheel(boolean) 1089 * @see #setMinValue(int) 1090 * @see #setMaxValue(int) 1091 */ 1092 public void setValue(int value) { 1093 if (mValue == value) { 1094 return; 1095 } 1096 setValueInternal(value, false); 1097 initializeSelectorWheelIndices(); 1098 invalidate(); 1099 } 1100 1101 /** 1102 * Shows the soft input for its input text. 1103 */ 1104 private void showSoftInput() { 1105 InputMethodManager inputMethodManager = InputMethodManager.peekInstance(); 1106 if (inputMethodManager != null) { 1107 if (mHasSelectorWheel) { 1108 mInputText.setVisibility(View.VISIBLE); 1109 } 1110 mInputText.requestFocus(); 1111 inputMethodManager.showSoftInput(mInputText, 0); 1112 } 1113 } 1114 1115 /** 1116 * Hides the soft input if it is active for the input text. 1117 */ 1118 private void hideSoftInput() { 1119 InputMethodManager inputMethodManager = InputMethodManager.peekInstance(); 1120 if (inputMethodManager != null && inputMethodManager.isActive(mInputText)) { 1121 inputMethodManager.hideSoftInputFromWindow(getWindowToken(), 0); 1122 if (mHasSelectorWheel) { 1123 mInputText.setVisibility(View.INVISIBLE); 1124 } 1125 } 1126 } 1127 1128 /** 1129 * Computes the max width if no such specified as an attribute. 1130 */ 1131 private void tryComputeMaxWidth() { 1132 if (!mComputeMaxWidth) { 1133 return; 1134 } 1135 int maxTextWidth = 0; 1136 if (mDisplayedValues == null) { 1137 float maxDigitWidth = 0; 1138 for (int i = 0; i <= 9; i++) { 1139 final float digitWidth = mSelectorWheelPaint.measureText(String.valueOf(i)); 1140 if (digitWidth > maxDigitWidth) { 1141 maxDigitWidth = digitWidth; 1142 } 1143 } 1144 int numberOfDigits = 0; 1145 int current = mMaxValue; 1146 while (current > 0) { 1147 numberOfDigits++; 1148 current = current / 10; 1149 } 1150 maxTextWidth = (int) (numberOfDigits * maxDigitWidth); 1151 } else { 1152 final int valueCount = mDisplayedValues.length; 1153 for (int i = 0; i < valueCount; i++) { 1154 final float textWidth = mSelectorWheelPaint.measureText(mDisplayedValues[i]); 1155 if (textWidth > maxTextWidth) { 1156 maxTextWidth = (int) textWidth; 1157 } 1158 } 1159 } 1160 maxTextWidth += mInputText.getPaddingLeft() + mInputText.getPaddingRight(); 1161 if (mMaxWidth != maxTextWidth) { 1162 if (maxTextWidth > mMinWidth) { 1163 mMaxWidth = maxTextWidth; 1164 } else { 1165 mMaxWidth = mMinWidth; 1166 } 1167 invalidate(); 1168 } 1169 } 1170 1171 /** 1172 * Gets whether the selector wheel wraps when reaching the min/max value. 1173 * 1174 * @return True if the selector wheel wraps. 1175 * 1176 * @see #getMinValue() 1177 * @see #getMaxValue() 1178 */ 1179 public boolean getWrapSelectorWheel() { 1180 return mWrapSelectorWheel; 1181 } 1182 1183 /** 1184 * Sets whether the selector wheel shown during flinging/scrolling should 1185 * wrap around the {@link NumberPicker#getMinValue()} and 1186 * {@link NumberPicker#getMaxValue()} values. 1187 * <p> 1188 * By default if the range (max - min) is more than the number of items shown 1189 * on the selector wheel the selector wheel wrapping is enabled. 1190 * </p> 1191 * <p> 1192 * <strong>Note:</strong> If the number of items, i.e. the range ( 1193 * {@link #getMaxValue()} - {@link #getMinValue()}) is less than 1194 * the number of items shown on the selector wheel, the selector wheel will 1195 * not wrap. Hence, in such a case calling this method is a NOP. 1196 * </p> 1197 * 1198 * @param wrapSelectorWheel Whether to wrap. 1199 */ 1200 public void setWrapSelectorWheel(boolean wrapSelectorWheel) { 1201 final boolean wrappingAllowed = (mMaxValue - mMinValue) >= mSelectorIndices.length; 1202 if ((!wrapSelectorWheel || wrappingAllowed) && wrapSelectorWheel != mWrapSelectorWheel) { 1203 mWrapSelectorWheel = wrapSelectorWheel; 1204 } 1205 } 1206 1207 /** 1208 * Sets the speed at which the numbers be incremented and decremented when 1209 * the up and down buttons are long pressed respectively. 1210 * <p> 1211 * The default value is 300 ms. 1212 * </p> 1213 * 1214 * @param intervalMillis The speed (in milliseconds) at which the numbers 1215 * will be incremented and decremented. 1216 */ 1217 public void setOnLongPressUpdateInterval(long intervalMillis) { 1218 mLongPressUpdateInterval = intervalMillis; 1219 } 1220 1221 /** 1222 * Returns the value of the picker. 1223 * 1224 * @return The value. 1225 */ 1226 public int getValue() { 1227 return mValue; 1228 } 1229 1230 /** 1231 * Returns the min value of the picker. 1232 * 1233 * @return The min value 1234 */ 1235 public int getMinValue() { 1236 return mMinValue; 1237 } 1238 1239 /** 1240 * Sets the min value of the picker. 1241 * 1242 * @param minValue The min value. 1243 */ 1244 public void setMinValue(int minValue) { 1245 if (mMinValue == minValue) { 1246 return; 1247 } 1248 if (minValue < 0) { 1249 throw new IllegalArgumentException("minValue must be >= 0"); 1250 } 1251 mMinValue = minValue; 1252 if (mMinValue > mValue) { 1253 mValue = mMinValue; 1254 } 1255 boolean wrapSelectorWheel = mMaxValue - mMinValue > mSelectorIndices.length; 1256 setWrapSelectorWheel(wrapSelectorWheel); 1257 initializeSelectorWheelIndices(); 1258 updateInputTextView(); 1259 tryComputeMaxWidth(); 1260 invalidate(); 1261 } 1262 1263 /** 1264 * Returns the max value of the picker. 1265 * 1266 * @return The max value. 1267 */ 1268 public int getMaxValue() { 1269 return mMaxValue; 1270 } 1271 1272 /** 1273 * Sets the max value of the picker. 1274 * 1275 * @param maxValue The max value. 1276 */ 1277 public void setMaxValue(int maxValue) { 1278 if (mMaxValue == maxValue) { 1279 return; 1280 } 1281 if (maxValue < 0) { 1282 throw new IllegalArgumentException("maxValue must be >= 0"); 1283 } 1284 mMaxValue = maxValue; 1285 if (mMaxValue < mValue) { 1286 mValue = mMaxValue; 1287 } 1288 boolean wrapSelectorWheel = mMaxValue - mMinValue > mSelectorIndices.length; 1289 setWrapSelectorWheel(wrapSelectorWheel); 1290 initializeSelectorWheelIndices(); 1291 updateInputTextView(); 1292 tryComputeMaxWidth(); 1293 invalidate(); 1294 } 1295 1296 /** 1297 * Gets the values to be displayed instead of string values. 1298 * 1299 * @return The displayed values. 1300 */ 1301 public String[] getDisplayedValues() { 1302 return mDisplayedValues; 1303 } 1304 1305 /** 1306 * Sets the values to be displayed. 1307 * 1308 * @param displayedValues The displayed values. 1309 */ 1310 public void setDisplayedValues(String[] displayedValues) { 1311 if (mDisplayedValues == displayedValues) { 1312 return; 1313 } 1314 mDisplayedValues = displayedValues; 1315 if (mDisplayedValues != null) { 1316 // Allow text entry rather than strictly numeric entry. 1317 mInputText.setRawInputType(InputType.TYPE_CLASS_TEXT 1318 | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); 1319 } else { 1320 mInputText.setRawInputType(InputType.TYPE_CLASS_NUMBER); 1321 } 1322 updateInputTextView(); 1323 initializeSelectorWheelIndices(); 1324 tryComputeMaxWidth(); 1325 } 1326 1327 @Override 1328 protected float getTopFadingEdgeStrength() { 1329 return TOP_AND_BOTTOM_FADING_EDGE_STRENGTH; 1330 } 1331 1332 @Override 1333 protected float getBottomFadingEdgeStrength() { 1334 return TOP_AND_BOTTOM_FADING_EDGE_STRENGTH; 1335 } 1336 1337 @Override 1338 protected void onDetachedFromWindow() { 1339 removeAllCallbacks(); 1340 } 1341 1342 @Override 1343 protected void onDraw(Canvas canvas) { 1344 if (!mHasSelectorWheel) { 1345 super.onDraw(canvas); 1346 return; 1347 } 1348 float x = (mRight - mLeft) / 2; 1349 float y = mCurrentScrollOffset; 1350 1351 // draw the selector wheel 1352 int[] selectorIndices = mSelectorIndices; 1353 for (int i = 0; i < selectorIndices.length; i++) { 1354 int selectorIndex = selectorIndices[i]; 1355 String scrollSelectorValue = mSelectorIndexToStringCache.get(selectorIndex); 1356 // Do not draw the middle item if input is visible since the input 1357 // is shown only if the wheel is static and it covers the middle 1358 // item. Otherwise, if the user starts editing the text via the 1359 // IME he may see a dimmed version of the old value intermixed 1360 // with the new one. 1361 if (i != SELECTOR_MIDDLE_ITEM_INDEX || mInputText.getVisibility() != VISIBLE) { 1362 canvas.drawText(scrollSelectorValue, x, y, mSelectorWheelPaint); 1363 } 1364 y += mSelectorElementHeight; 1365 } 1366 1367 // draw the selection dividers 1368 if (mSelectionDivider != null) { 1369 // draw the top divider 1370 int topOfTopDivider = mTopSelectionDividerTop; 1371 int bottomOfTopDivider = topOfTopDivider + mSelectionDividerHeight; 1372 mSelectionDivider.setBounds(0, topOfTopDivider, mRight, bottomOfTopDivider); 1373 mSelectionDivider.draw(canvas); 1374 1375 // draw the bottom divider 1376 int bottomOfBottomDivider = mBottomSelectionDividerBottom; 1377 int topOfBottomDivider = bottomOfBottomDivider - mSelectionDividerHeight; 1378 mSelectionDivider.setBounds(0, topOfBottomDivider, mRight, bottomOfBottomDivider); 1379 mSelectionDivider.draw(canvas); 1380 } 1381 } 1382 1383 @Override 1384 public void sendAccessibilityEvent(int eventType) { 1385 // Do not send accessibility events - we want the user to 1386 // perceive this widget as several controls rather as a whole. 1387 } 1388 1389 @Override 1390 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 1391 super.onInitializeAccessibilityEvent(event); 1392 event.setClassName(NumberPicker.class.getName()); 1393 event.setScrollable(true); 1394 event.setScrollY((mMinValue + mValue) * mSelectorElementHeight); 1395 event.setMaxScrollY((mMaxValue - mMinValue) * mSelectorElementHeight); 1396 } 1397 1398 @Override 1399 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 1400 if (!mHasSelectorWheel) { 1401 return super.getAccessibilityNodeProvider(); 1402 } 1403 if (mAccessibilityNodeProvider == null) { 1404 mAccessibilityNodeProvider = new AccessibilityNodeProviderImpl(); 1405 } 1406 return mAccessibilityNodeProvider; 1407 } 1408 1409 /** 1410 * Makes a measure spec that tries greedily to use the max value. 1411 * 1412 * @param measureSpec The measure spec. 1413 * @param maxSize The max value for the size. 1414 * @return A measure spec greedily imposing the max size. 1415 */ 1416 private int makeMeasureSpec(int measureSpec, int maxSize) { 1417 if (maxSize == SIZE_UNSPECIFIED) { 1418 return measureSpec; 1419 } 1420 final int size = MeasureSpec.getSize(measureSpec); 1421 final int mode = MeasureSpec.getMode(measureSpec); 1422 switch (mode) { 1423 case MeasureSpec.EXACTLY: 1424 return measureSpec; 1425 case MeasureSpec.AT_MOST: 1426 return MeasureSpec.makeMeasureSpec(Math.min(size, maxSize), MeasureSpec.EXACTLY); 1427 case MeasureSpec.UNSPECIFIED: 1428 return MeasureSpec.makeMeasureSpec(maxSize, MeasureSpec.EXACTLY); 1429 default: 1430 throw new IllegalArgumentException("Unknown measure mode: " + mode); 1431 } 1432 } 1433 1434 /** 1435 * Utility to reconcile a desired size and state, with constraints imposed 1436 * by a MeasureSpec. Tries to respect the min size, unless a different size 1437 * is imposed by the constraints. 1438 * 1439 * @param minSize The minimal desired size. 1440 * @param measuredSize The currently measured size. 1441 * @param measureSpec The current measure spec. 1442 * @return The resolved size and state. 1443 */ 1444 private int resolveSizeAndStateRespectingMinSize( 1445 int minSize, int measuredSize, int measureSpec) { 1446 if (minSize != SIZE_UNSPECIFIED) { 1447 final int desiredWidth = Math.max(minSize, measuredSize); 1448 return resolveSizeAndState(desiredWidth, measureSpec, 0); 1449 } else { 1450 return measuredSize; 1451 } 1452 } 1453 1454 /** 1455 * Resets the selector indices and clear the cached string representation of 1456 * these indices. 1457 */ 1458 private void initializeSelectorWheelIndices() { 1459 mSelectorIndexToStringCache.clear(); 1460 int[] selectorIdices = mSelectorIndices; 1461 int current = getValue(); 1462 for (int i = 0; i < mSelectorIndices.length; i++) { 1463 int selectorIndex = current + (i - SELECTOR_MIDDLE_ITEM_INDEX); 1464 if (mWrapSelectorWheel) { 1465 selectorIndex = getWrappedSelectorIndex(selectorIndex); 1466 } 1467 mSelectorIndices[i] = selectorIndex; 1468 ensureCachedScrollSelectorValue(mSelectorIndices[i]); 1469 } 1470 } 1471 1472 /** 1473 * Sets the current value of this NumberPicker. 1474 * 1475 * @param current The new value of the NumberPicker. 1476 * @param notifyChange Whether to notify if the current value changed. 1477 */ 1478 private void setValueInternal(int current, boolean notifyChange) { 1479 if (mValue == current) { 1480 return; 1481 } 1482 // Wrap around the values if we go past the start or end 1483 if (mWrapSelectorWheel) { 1484 current = getWrappedSelectorIndex(current); 1485 } else { 1486 current = Math.max(current, mMinValue); 1487 current = Math.min(current, mMaxValue); 1488 } 1489 int previous = mValue; 1490 mValue = current; 1491 updateInputTextView(); 1492 if (notifyChange) { 1493 notifyChange(previous, current); 1494 } 1495 } 1496 1497 /** 1498 * Changes the current value by one which is increment or 1499 * decrement based on the passes argument. 1500 * decrement the current value. 1501 * 1502 * @param increment True to increment, false to decrement. 1503 */ 1504 private void changeValueByOne(boolean increment) { 1505 if (mHasSelectorWheel) { 1506 mInputText.setVisibility(View.INVISIBLE); 1507 if (!moveToFinalScrollerPosition(mFlingScroller)) { 1508 moveToFinalScrollerPosition(mAdjustScroller); 1509 } 1510 mPreviousScrollerY = 0; 1511 if (increment) { 1512 mFlingScroller.startScroll(0, 0, 0, -mSelectorElementHeight, 1513 CHANGE_CURRENT_BY_ONE_SCROLL_DURATION); 1514 } else { 1515 mFlingScroller.startScroll(0, 0, 0, mSelectorElementHeight, 1516 CHANGE_CURRENT_BY_ONE_SCROLL_DURATION); 1517 } 1518 invalidate(); 1519 } else { 1520 if (increment) { 1521 setValueInternal(mValue + 1, true); 1522 } else { 1523 setValueInternal(mValue - 1, true); 1524 } 1525 } 1526 } 1527 1528 private void initializeSelectorWheel() { 1529 initializeSelectorWheelIndices(); 1530 int[] selectorIndices = mSelectorIndices; 1531 int totalTextHeight = selectorIndices.length * mTextSize; 1532 float totalTextGapHeight = (mBottom - mTop) - totalTextHeight; 1533 float textGapCount = selectorIndices.length; 1534 mSelectorTextGapHeight = (int) (totalTextGapHeight / textGapCount + 0.5f); 1535 mSelectorElementHeight = mTextSize + mSelectorTextGapHeight; 1536 // Ensure that the middle item is positioned the same as the text in 1537 // mInputText 1538 int editTextTextPosition = mInputText.getBaseline() + mInputText.getTop(); 1539 mInitialScrollOffset = editTextTextPosition 1540 - (mSelectorElementHeight * SELECTOR_MIDDLE_ITEM_INDEX); 1541 mCurrentScrollOffset = mInitialScrollOffset; 1542 updateInputTextView(); 1543 } 1544 1545 private void initializeFadingEdges() { 1546 setVerticalFadingEdgeEnabled(true); 1547 setFadingEdgeLength((mBottom - mTop - mTextSize) / 2); 1548 } 1549 1550 /** 1551 * Callback invoked upon completion of a given <code>scroller</code>. 1552 */ 1553 private void onScrollerFinished(Scroller scroller) { 1554 if (scroller == mFlingScroller) { 1555 if (!ensureScrollWheelAdjusted()) { 1556 updateInputTextView(); 1557 } 1558 onScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); 1559 } else { 1560 if (mScrollState != OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { 1561 updateInputTextView(); 1562 } 1563 } 1564 } 1565 1566 /** 1567 * Handles transition to a given <code>scrollState</code> 1568 */ 1569 private void onScrollStateChange(int scrollState) { 1570 if (mScrollState == scrollState) { 1571 return; 1572 } 1573 mScrollState = scrollState; 1574 if (mOnScrollListener != null) { 1575 mOnScrollListener.onScrollStateChange(this, scrollState); 1576 } 1577 } 1578 1579 /** 1580 * Flings the selector with the given <code>velocityY</code>. 1581 */ 1582 private void fling(int velocityY) { 1583 mPreviousScrollerY = 0; 1584 1585 if (velocityY > 0) { 1586 mFlingScroller.fling(0, 0, 0, velocityY, 0, 0, 0, Integer.MAX_VALUE); 1587 } else { 1588 mFlingScroller.fling(0, Integer.MAX_VALUE, 0, velocityY, 0, 0, 0, Integer.MAX_VALUE); 1589 } 1590 1591 invalidate(); 1592 } 1593 1594 /** 1595 * @return The wrapped index <code>selectorIndex</code> value. 1596 */ 1597 private int getWrappedSelectorIndex(int selectorIndex) { 1598 if (selectorIndex > mMaxValue) { 1599 return mMinValue + (selectorIndex - mMaxValue) % (mMaxValue - mMinValue) - 1; 1600 } else if (selectorIndex < mMinValue) { 1601 return mMaxValue - (mMinValue - selectorIndex) % (mMaxValue - mMinValue) + 1; 1602 } 1603 return selectorIndex; 1604 } 1605 1606 /** 1607 * Increments the <code>selectorIndices</code> whose string representations 1608 * will be displayed in the selector. 1609 */ 1610 private void incrementSelectorIndices(int[] selectorIndices) { 1611 for (int i = 0; i < selectorIndices.length - 1; i++) { 1612 selectorIndices[i] = selectorIndices[i + 1]; 1613 } 1614 int nextScrollSelectorIndex = selectorIndices[selectorIndices.length - 2] + 1; 1615 if (mWrapSelectorWheel && nextScrollSelectorIndex > mMaxValue) { 1616 nextScrollSelectorIndex = mMinValue; 1617 } 1618 selectorIndices[selectorIndices.length - 1] = nextScrollSelectorIndex; 1619 ensureCachedScrollSelectorValue(nextScrollSelectorIndex); 1620 } 1621 1622 /** 1623 * Decrements the <code>selectorIndices</code> whose string representations 1624 * will be displayed in the selector. 1625 */ 1626 private void decrementSelectorIndices(int[] selectorIndices) { 1627 for (int i = selectorIndices.length - 1; i > 0; i--) { 1628 selectorIndices[i] = selectorIndices[i - 1]; 1629 } 1630 int nextScrollSelectorIndex = selectorIndices[1] - 1; 1631 if (mWrapSelectorWheel && nextScrollSelectorIndex < mMinValue) { 1632 nextScrollSelectorIndex = mMaxValue; 1633 } 1634 selectorIndices[0] = nextScrollSelectorIndex; 1635 ensureCachedScrollSelectorValue(nextScrollSelectorIndex); 1636 } 1637 1638 /** 1639 * Ensures we have a cached string representation of the given <code> 1640 * selectorIndex</code> to avoid multiple instantiations of the same string. 1641 */ 1642 private void ensureCachedScrollSelectorValue(int selectorIndex) { 1643 SparseArray<String> cache = mSelectorIndexToStringCache; 1644 String scrollSelectorValue = cache.get(selectorIndex); 1645 if (scrollSelectorValue != null) { 1646 return; 1647 } 1648 if (selectorIndex < mMinValue || selectorIndex > mMaxValue) { 1649 scrollSelectorValue = ""; 1650 } else { 1651 if (mDisplayedValues != null) { 1652 int displayedValueIndex = selectorIndex - mMinValue; 1653 scrollSelectorValue = mDisplayedValues[displayedValueIndex]; 1654 } else { 1655 scrollSelectorValue = formatNumber(selectorIndex); 1656 } 1657 } 1658 cache.put(selectorIndex, scrollSelectorValue); 1659 } 1660 1661 private String formatNumber(int value) { 1662 return (mFormatter != null) ? mFormatter.format(value) : String.valueOf(value); 1663 } 1664 1665 private void validateInputTextView(View v) { 1666 String str = String.valueOf(((TextView) v).getText()); 1667 if (TextUtils.isEmpty(str)) { 1668 // Restore to the old value as we don't allow empty values 1669 updateInputTextView(); 1670 } else { 1671 // Check the new value and ensure it's in range 1672 int current = getSelectedPos(str.toString()); 1673 setValueInternal(current, true); 1674 } 1675 } 1676 1677 /** 1678 * Updates the view of this NumberPicker. If displayValues were specified in 1679 * the string corresponding to the index specified by the current value will 1680 * be returned. Otherwise, the formatter specified in {@link #setFormatter} 1681 * will be used to format the number. 1682 * 1683 * @return Whether the text was updated. 1684 */ 1685 private boolean updateInputTextView() { 1686 /* 1687 * If we don't have displayed values then use the current number else 1688 * find the correct value in the displayed values for the current 1689 * number. 1690 */ 1691 String text = (mDisplayedValues == null) ? formatNumber(mValue) 1692 : mDisplayedValues[mValue - mMinValue]; 1693 if (!TextUtils.isEmpty(text) && !text.equals(mInputText.getText().toString())) { 1694 mInputText.setText(text); 1695 return true; 1696 } 1697 1698 return false; 1699 } 1700 1701 /** 1702 * Notifies the listener, if registered, of a change of the value of this 1703 * NumberPicker. 1704 */ 1705 private void notifyChange(int previous, int current) { 1706 if (mOnValueChangeListener != null) { 1707 mOnValueChangeListener.onValueChange(this, previous, mValue); 1708 } 1709 } 1710 1711 /** 1712 * Posts a command for changing the current value by one. 1713 * 1714 * @param increment Whether to increment or decrement the value. 1715 */ 1716 private void postChangeCurrentByOneFromLongPress(boolean increment, long delayMillis) { 1717 if (mChangeCurrentByOneFromLongPressCommand == null) { 1718 mChangeCurrentByOneFromLongPressCommand = new ChangeCurrentByOneFromLongPressCommand(); 1719 } else { 1720 removeCallbacks(mChangeCurrentByOneFromLongPressCommand); 1721 } 1722 mChangeCurrentByOneFromLongPressCommand.setStep(increment); 1723 postDelayed(mChangeCurrentByOneFromLongPressCommand, delayMillis); 1724 } 1725 1726 /** 1727 * Removes the command for changing the current value by one. 1728 */ 1729 private void removeChangeCurrentByOneFromLongPress() { 1730 if (mChangeCurrentByOneFromLongPressCommand != null) { 1731 removeCallbacks(mChangeCurrentByOneFromLongPressCommand); 1732 } 1733 } 1734 1735 /** 1736 * Posts a command for beginning an edit of the current value via IME on 1737 * long press. 1738 */ 1739 private void postBeginSoftInputOnLongPressCommand() { 1740 if (mBeginSoftInputOnLongPressCommand == null) { 1741 mBeginSoftInputOnLongPressCommand = new BeginSoftInputOnLongPressCommand(); 1742 } else { 1743 removeCallbacks(mBeginSoftInputOnLongPressCommand); 1744 } 1745 postDelayed(mBeginSoftInputOnLongPressCommand, ViewConfiguration.getLongPressTimeout()); 1746 } 1747 1748 /** 1749 * Removes the command for beginning an edit of the current value via IME. 1750 */ 1751 private void removeBeginSoftInputCommand() { 1752 if (mBeginSoftInputOnLongPressCommand != null) { 1753 removeCallbacks(mBeginSoftInputOnLongPressCommand); 1754 } 1755 } 1756 1757 /** 1758 * Removes all pending callback from the message queue. 1759 */ 1760 private void removeAllCallbacks() { 1761 if (mChangeCurrentByOneFromLongPressCommand != null) { 1762 removeCallbacks(mChangeCurrentByOneFromLongPressCommand); 1763 } 1764 if (mSetSelectionCommand != null) { 1765 removeCallbacks(mSetSelectionCommand); 1766 } 1767 if (mBeginSoftInputOnLongPressCommand != null) { 1768 removeCallbacks(mBeginSoftInputOnLongPressCommand); 1769 } 1770 } 1771 1772 /** 1773 * @return The selected index given its displayed <code>value</code>. 1774 */ 1775 private int getSelectedPos(String value) { 1776 if (mDisplayedValues == null) { 1777 try { 1778 return Integer.parseInt(value); 1779 } catch (NumberFormatException e) { 1780 // Ignore as if it's not a number we don't care 1781 } 1782 } else { 1783 for (int i = 0; i < mDisplayedValues.length; i++) { 1784 // Don't force the user to type in jan when ja will do 1785 value = value.toLowerCase(); 1786 if (mDisplayedValues[i].toLowerCase().startsWith(value)) { 1787 return mMinValue + i; 1788 } 1789 } 1790 1791 /* 1792 * The user might have typed in a number into the month field i.e. 1793 * 10 instead of OCT so support that too. 1794 */ 1795 try { 1796 return Integer.parseInt(value); 1797 } catch (NumberFormatException e) { 1798 1799 // Ignore as if it's not a number we don't care 1800 } 1801 } 1802 return mMinValue; 1803 } 1804 1805 /** 1806 * Posts an {@link SetSelectionCommand} from the given <code>selectionStart 1807 * </code> to <code>selectionEnd</code>. 1808 */ 1809 private void postSetSelectionCommand(int selectionStart, int selectionEnd) { 1810 if (mSetSelectionCommand == null) { 1811 mSetSelectionCommand = new SetSelectionCommand(); 1812 } else { 1813 removeCallbacks(mSetSelectionCommand); 1814 } 1815 mSetSelectionCommand.mSelectionStart = selectionStart; 1816 mSetSelectionCommand.mSelectionEnd = selectionEnd; 1817 post(mSetSelectionCommand); 1818 } 1819 1820 /** 1821 * Filter for accepting only valid indices or prefixes of the string 1822 * representation of valid indices. 1823 */ 1824 class InputTextFilter extends NumberKeyListener { 1825 1826 // XXX This doesn't allow for range limits when controlled by a 1827 // soft input method! 1828 public int getInputType() { 1829 return InputType.TYPE_CLASS_TEXT; 1830 } 1831 1832 @Override 1833 protected char[] getAcceptedChars() { 1834 return DIGIT_CHARACTERS; 1835 } 1836 1837 @Override 1838 public CharSequence filter( 1839 CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 1840 if (mDisplayedValues == null) { 1841 CharSequence filtered = super.filter(source, start, end, dest, dstart, dend); 1842 if (filtered == null) { 1843 filtered = source.subSequence(start, end); 1844 } 1845 1846 String result = String.valueOf(dest.subSequence(0, dstart)) + filtered 1847 + dest.subSequence(dend, dest.length()); 1848 1849 if ("".equals(result)) { 1850 return result; 1851 } 1852 int val = getSelectedPos(result); 1853 1854 /* 1855 * Ensure the user can't type in a value greater than the max 1856 * allowed. We have to allow less than min as the user might 1857 * want to delete some numbers and then type a new number. 1858 */ 1859 if (val > mMaxValue) { 1860 return ""; 1861 } else { 1862 return filtered; 1863 } 1864 } else { 1865 CharSequence filtered = String.valueOf(source.subSequence(start, end)); 1866 if (TextUtils.isEmpty(filtered)) { 1867 return ""; 1868 } 1869 String result = String.valueOf(dest.subSequence(0, dstart)) + filtered 1870 + dest.subSequence(dend, dest.length()); 1871 String str = String.valueOf(result).toLowerCase(); 1872 for (String val : mDisplayedValues) { 1873 String valLowerCase = val.toLowerCase(); 1874 if (valLowerCase.startsWith(str)) { 1875 postSetSelectionCommand(result.length(), val.length()); 1876 return val.subSequence(dstart, val.length()); 1877 } 1878 } 1879 return ""; 1880 } 1881 } 1882 } 1883 1884 /** 1885 * Ensures that the scroll wheel is adjusted i.e. there is no offset and the 1886 * middle element is in the middle of the widget. 1887 * 1888 * @return Whether an adjustment has been made. 1889 */ 1890 private boolean ensureScrollWheelAdjusted() { 1891 // adjust to the closest value 1892 int deltaY = mInitialScrollOffset - mCurrentScrollOffset; 1893 if (deltaY != 0) { 1894 mPreviousScrollerY = 0; 1895 if (Math.abs(deltaY) > mSelectorElementHeight / 2) { 1896 deltaY += (deltaY > 0) ? -mSelectorElementHeight : mSelectorElementHeight; 1897 } 1898 mAdjustScroller.startScroll(0, 0, 0, deltaY, SELECTOR_ADJUSTMENT_DURATION_MILLIS); 1899 invalidate(); 1900 return true; 1901 } 1902 return false; 1903 } 1904 1905 /** 1906 * Command for setting the input text selection. 1907 */ 1908 class SetSelectionCommand implements Runnable { 1909 private int mSelectionStart; 1910 1911 private int mSelectionEnd; 1912 1913 public void run() { 1914 mInputText.setSelection(mSelectionStart, mSelectionEnd); 1915 } 1916 } 1917 1918 /** 1919 * Command for changing the current value from a long press by one. 1920 */ 1921 class ChangeCurrentByOneFromLongPressCommand implements Runnable { 1922 private boolean mIncrement; 1923 1924 private void setStep(boolean increment) { 1925 mIncrement = increment; 1926 } 1927 1928 @Override 1929 public void run() { 1930 changeValueByOne(mIncrement); 1931 postDelayed(this, mLongPressUpdateInterval); 1932 } 1933 } 1934 1935 /** 1936 * @hide 1937 */ 1938 public static class CustomEditText extends EditText { 1939 1940 public CustomEditText(Context context, AttributeSet attrs) { 1941 super(context, attrs); 1942 } 1943 1944 @Override 1945 public void onEditorAction(int actionCode) { 1946 super.onEditorAction(actionCode); 1947 if (actionCode == EditorInfo.IME_ACTION_DONE) { 1948 clearFocus(); 1949 } 1950 } 1951 } 1952 1953 /** 1954 * Command for beginning soft input on long press. 1955 */ 1956 class BeginSoftInputOnLongPressCommand implements Runnable { 1957 1958 @Override 1959 public void run() { 1960 showSoftInput(); 1961 mIngonreMoveEvents = true; 1962 } 1963 } 1964 1965 class AccessibilityNodeProviderImpl extends AccessibilityNodeProvider { 1966 private static final int VIRTUAL_VIEW_ID_INCREMENT = 1; 1967 1968 private static final int VIRTUAL_VIEW_ID_INPUT = 2; 1969 1970 private static final int VIRTUAL_VIEW_ID_DECREMENT = 3; 1971 1972 private final Rect mTempRect = new Rect(); 1973 1974 private final int[] mTempArray = new int[2]; 1975 1976 @Override 1977 public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) { 1978 switch (virtualViewId) { 1979 case View.NO_ID: 1980 return createAccessibilityNodeInfoForNumberPicker( mScrollX, mScrollY, 1981 mScrollX + (mRight - mLeft), mScrollY + (mBottom - mTop)); 1982 case VIRTUAL_VIEW_ID_DECREMENT: 1983 return createAccessibilityNodeInfoForVirtualButton(VIRTUAL_VIEW_ID_DECREMENT, 1984 getVirtualDecrementButtonText(), mScrollX, mScrollY, 1985 mScrollX + (mRight - mLeft), 1986 mTopSelectionDividerTop + mSelectionDividerHeight); 1987 case VIRTUAL_VIEW_ID_INPUT: 1988 return createAccessibiltyNodeInfoForInputText(); 1989 case VIRTUAL_VIEW_ID_INCREMENT: 1990 return createAccessibilityNodeInfoForVirtualButton(VIRTUAL_VIEW_ID_INCREMENT, 1991 getVirtualIncrementButtonText(), mScrollX, 1992 mBottomSelectionDividerBottom - mSelectionDividerHeight, 1993 mScrollX + (mRight - mLeft), mScrollY + (mBottom - mTop)); 1994 } 1995 return super.createAccessibilityNodeInfo(virtualViewId); 1996 } 1997 1998 @Override 1999 public List<AccessibilityNodeInfo> findAccessibilityNodeInfosByText(String searched, 2000 int virtualViewId) { 2001 if (TextUtils.isEmpty(searched)) { 2002 return Collections.emptyList(); 2003 } 2004 String searchedLowerCase = searched.toLowerCase(); 2005 List<AccessibilityNodeInfo> result = new ArrayList<AccessibilityNodeInfo>(); 2006 switch (virtualViewId) { 2007 case View.NO_ID: { 2008 findAccessibilityNodeInfosByTextInChild(searchedLowerCase, 2009 VIRTUAL_VIEW_ID_DECREMENT, result); 2010 findAccessibilityNodeInfosByTextInChild(searchedLowerCase, 2011 VIRTUAL_VIEW_ID_INPUT, result); 2012 findAccessibilityNodeInfosByTextInChild(searchedLowerCase, 2013 VIRTUAL_VIEW_ID_INCREMENT, result); 2014 return result; 2015 } 2016 case VIRTUAL_VIEW_ID_DECREMENT: 2017 case VIRTUAL_VIEW_ID_INCREMENT: 2018 case VIRTUAL_VIEW_ID_INPUT: { 2019 findAccessibilityNodeInfosByTextInChild(searchedLowerCase, virtualViewId, 2020 result); 2021 return result; 2022 } 2023 } 2024 return super.findAccessibilityNodeInfosByText(searched, virtualViewId); 2025 } 2026 2027 @Override 2028 public boolean performAccessibilityAction(int action, int virtualViewId) { 2029 switch (virtualViewId) { 2030 case VIRTUAL_VIEW_ID_INPUT: { 2031 switch (action) { 2032 case AccessibilityNodeInfo.ACTION_FOCUS: { 2033 if (!mInputText.isFocused()) { 2034 return mInputText.requestFocus(); 2035 } 2036 } break; 2037 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 2038 if (mInputText.isFocused()) { 2039 mInputText.clearFocus(); 2040 return true; 2041 } 2042 } break; 2043 } 2044 } break; 2045 } 2046 return super.performAccessibilityAction(action, virtualViewId); 2047 } 2048 2049 public void sendAccessibilityEventForVirtualView(int virtualViewId, int eventType) { 2050 switch (virtualViewId) { 2051 case VIRTUAL_VIEW_ID_DECREMENT: { 2052 sendAccessibilityEventForVirtualButton(virtualViewId, eventType, 2053 getVirtualDecrementButtonText()); 2054 } break; 2055 case VIRTUAL_VIEW_ID_INPUT: { 2056 sendAccessibilityEventForVirtualText(eventType); 2057 } break; 2058 case VIRTUAL_VIEW_ID_INCREMENT: { 2059 sendAccessibilityEventForVirtualButton(virtualViewId, eventType, 2060 getVirtualIncrementButtonText()); 2061 } break; 2062 } 2063 } 2064 2065 private void sendAccessibilityEventForVirtualText(int eventType) { 2066 AccessibilityEvent event = AccessibilityEvent.obtain(eventType); 2067 mInputText.onInitializeAccessibilityEvent(event); 2068 mInputText.onPopulateAccessibilityEvent(event); 2069 event.setSource(NumberPicker.this, VIRTUAL_VIEW_ID_INPUT); 2070 requestSendAccessibilityEvent(NumberPicker.this, event); 2071 } 2072 2073 private void sendAccessibilityEventForVirtualButton(int virtualViewId, int eventType, 2074 String text) { 2075 AccessibilityEvent event = AccessibilityEvent.obtain(eventType); 2076 event.setClassName(Button.class.getName()); 2077 event.setPackageName(mContext.getPackageName()); 2078 event.getText().add(text); 2079 event.setEnabled(NumberPicker.this.isEnabled()); 2080 event.setSource(NumberPicker.this, virtualViewId); 2081 requestSendAccessibilityEvent(NumberPicker.this, event); 2082 } 2083 2084 private void findAccessibilityNodeInfosByTextInChild(String searchedLowerCase, 2085 int virtualViewId, List<AccessibilityNodeInfo> outResult) { 2086 switch (virtualViewId) { 2087 case VIRTUAL_VIEW_ID_DECREMENT: { 2088 String text = getVirtualDecrementButtonText(); 2089 if (!TextUtils.isEmpty(text) 2090 && text.toString().toLowerCase().contains(searchedLowerCase)) { 2091 outResult.add(createAccessibilityNodeInfo(VIRTUAL_VIEW_ID_DECREMENT)); 2092 } 2093 } return; 2094 case VIRTUAL_VIEW_ID_INPUT: { 2095 CharSequence text = mInputText.getText(); 2096 if (!TextUtils.isEmpty(text) && 2097 text.toString().toLowerCase().contains(searchedLowerCase)) { 2098 outResult.add(createAccessibilityNodeInfo(VIRTUAL_VIEW_ID_INPUT)); 2099 return; 2100 } 2101 CharSequence contentDesc = mInputText.getText(); 2102 if (!TextUtils.isEmpty(contentDesc) && 2103 contentDesc.toString().toLowerCase().contains(searchedLowerCase)) { 2104 outResult.add(createAccessibilityNodeInfo(VIRTUAL_VIEW_ID_INPUT)); 2105 return; 2106 } 2107 } break; 2108 case VIRTUAL_VIEW_ID_INCREMENT: { 2109 String text = getVirtualIncrementButtonText(); 2110 if (!TextUtils.isEmpty(text) 2111 && text.toString().toLowerCase().contains(searchedLowerCase)) { 2112 outResult.add(createAccessibilityNodeInfo(VIRTUAL_VIEW_ID_INCREMENT)); 2113 } 2114 } return; 2115 } 2116 } 2117 2118 private AccessibilityNodeInfo createAccessibiltyNodeInfoForInputText() { 2119 AccessibilityNodeInfo info = mInputText.createAccessibilityNodeInfo(); 2120 info.setLongClickable(true); 2121 info.setSource(NumberPicker.this, VIRTUAL_VIEW_ID_INPUT); 2122 return info; 2123 } 2124 2125 private AccessibilityNodeInfo createAccessibilityNodeInfoForVirtualButton(int virtualViewId, 2126 String text, int left, int top, int right, int bottom) { 2127 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(); 2128 info.setClassName(Button.class.getName()); 2129 info.setPackageName(mContext.getPackageName()); 2130 info.setSource(NumberPicker.this, virtualViewId); 2131 info.setParent(NumberPicker.this); 2132 info.addChild(NumberPicker.this, VIRTUAL_VIEW_ID_DECREMENT); 2133 info.addChild(NumberPicker.this, VIRTUAL_VIEW_ID_INPUT); 2134 info.addChild(NumberPicker.this, VIRTUAL_VIEW_ID_INCREMENT); 2135 info.setText(text); 2136 info.setClickable(true); 2137 info.setLongClickable(true); 2138 info.setEnabled(NumberPicker.this.isEnabled()); 2139 Rect boundsInParent = mTempRect; 2140 boundsInParent.set(left, top, right, bottom); 2141 info.setBoundsInParent(boundsInParent); 2142 Rect boundsInScreen = boundsInParent; 2143 int[] locationOnScreen = mTempArray; 2144 getLocationOnScreen(locationOnScreen); 2145 boundsInScreen.offsetTo(0, 0); 2146 boundsInScreen.offset(locationOnScreen[0], locationOnScreen[1]); 2147 info.setBoundsInScreen(boundsInScreen); 2148 return info; 2149 } 2150 2151 private AccessibilityNodeInfo createAccessibilityNodeInfoForNumberPicker(int left, int top, 2152 int right, int bottom) { 2153 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(); 2154 info.setClassName(Button.class.getName()); 2155 info.setPackageName(mContext.getPackageName()); 2156 info.setSource(NumberPicker.this); 2157 info.setParent((View) getParent()); 2158 info.setEnabled(NumberPicker.this.isEnabled()); 2159 info.setScrollable(true); 2160 Rect boundsInParent = mTempRect; 2161 boundsInParent.set(left, top, right, bottom); 2162 info.setBoundsInParent(boundsInParent); 2163 Rect boundsInScreen = boundsInParent; 2164 int[] locationOnScreen = mTempArray; 2165 getLocationOnScreen(locationOnScreen); 2166 boundsInScreen.offsetTo(0, 0); 2167 boundsInScreen.offset(locationOnScreen[0], locationOnScreen[1]); 2168 info.setBoundsInScreen(boundsInScreen); 2169 return info; 2170 } 2171 2172 private String getVirtualDecrementButtonText() { 2173 int value = mValue - 1; 2174 if (mWrapSelectorWheel) { 2175 value = getWrappedSelectorIndex(value); 2176 } 2177 if (value >= mMinValue) { 2178 return (mDisplayedValues == null) ? formatNumber(value) 2179 : mDisplayedValues[value - mMinValue]; 2180 } 2181 return null; 2182 } 2183 2184 private String getVirtualIncrementButtonText() { 2185 int value = mValue + 1; 2186 if (mWrapSelectorWheel) { 2187 value = getWrappedSelectorIndex(value); 2188 } 2189 if (value <= mMaxValue) { 2190 return (mDisplayedValues == null) ? formatNumber(value) 2191 : mDisplayedValues[value - mMinValue]; 2192 } 2193 return null; 2194 } 2195 } 2196} 2197