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