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