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