This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
NumberPicker.java
2775 lines (2500 loc) · 104 KB
/
NumberPicker.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.widget;
import com.android.internal.R;
import android.annotation.CallSuper;
import android.annotation.IntDef;
import android.annotation.Widget;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.NumberKeyListener;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.LayoutInflater.Filter;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityNodeProvider;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import libcore.icu.LocaleData;
/**
* A widget that enables the user to select a number from a predefined range.
* There are two flavors of this widget and which one is presented to the user
* depends on the current theme.
* <ul>
* <li>
* If the current theme is derived from {@link android.R.style#Theme} the widget
* presents the current value as an editable input field with an increment button
* above and a decrement button below. Long pressing the buttons allows for a quick
* change of the current value. Tapping on the input field allows to type in
* a desired value.
* </li>
* <li>
* If the current theme is derived from {@link android.R.style#Theme_Holo} or
* {@link android.R.style#Theme_Holo_Light} the widget presents the current
* value as an editable input field with a lesser value above and a greater
* value below. Tapping on the lesser or greater value selects it by animating
* the number axis up or down to make the chosen value current. Flinging up
* or down allows for multiple increments or decrements of the current value.
* Long pressing on the lesser and greater values also allows for a quick change
* of the current value. Tapping on the current value allows to type in a
* desired value.
* </li>
* </ul>
* <p>
* For an example of using this widget, see {@link android.widget.TimePicker}.
* </p>
*/
@Widget
public class NumberPicker extends LinearLayout {
/**
* The number of items show in the selector wheel.
*/
private static final int SELECTOR_WHEEL_ITEM_COUNT = 3;
/**
* The default update interval during long press.
*/
private static final long DEFAULT_LONG_PRESS_UPDATE_INTERVAL = 300;
/**
* The index of the middle selector item.
*/
private static final int SELECTOR_MIDDLE_ITEM_INDEX = SELECTOR_WHEEL_ITEM_COUNT / 2;
/**
* The coefficient by which to adjust (divide) the max fling velocity.
*/
private static final int SELECTOR_MAX_FLING_VELOCITY_ADJUSTMENT = 8;
/**
* The the duration for adjusting the selector wheel.
*/
private static final int SELECTOR_ADJUSTMENT_DURATION_MILLIS = 800;
/**
* The duration of scrolling while snapping to a given position.
*/
private static final int SNAP_SCROLL_DURATION = 300;
/**
* The strength of fading in the top and bottom while drawing the selector.
*/
private static final float TOP_AND_BOTTOM_FADING_EDGE_STRENGTH = 0.9f;
/**
* The default unscaled height of the selection divider.
*/
private static final int UNSCALED_DEFAULT_SELECTION_DIVIDER_HEIGHT = 2;
/**
* The default unscaled distance between the selection dividers.
*/
private static final int UNSCALED_DEFAULT_SELECTION_DIVIDERS_DISTANCE = 48;
/**
* The resource id for the default layout.
*/
private static final int DEFAULT_LAYOUT_RESOURCE_ID = R.layout.number_picker;
/**
* Constant for unspecified size.
*/
private static final int SIZE_UNSPECIFIED = -1;
/**
* User choice on whether the selector wheel should be wrapped.
*/
private boolean mWrapSelectorWheelPreferred = true;
/**
* Use a custom NumberPicker formatting callback to use two-digit minutes
* strings like "01". Keeping a static formatter etc. is the most efficient
* way to do this; it avoids creating temporary objects on every call to
* format().
*/
private static class TwoDigitFormatter implements NumberPicker.Formatter {
final StringBuilder mBuilder = new StringBuilder();
char mZeroDigit;
java.util.Formatter mFmt;
final Object[] mArgs = new Object[1];
TwoDigitFormatter() {
final Locale locale = Locale.getDefault();
init(locale);
}
private void init(Locale locale) {
mFmt = createFormatter(locale);
mZeroDigit = getZeroDigit(locale);
}
public String format(int value) {
final Locale currentLocale = Locale.getDefault();
if (mZeroDigit != getZeroDigit(currentLocale)) {
init(currentLocale);
}
mArgs[0] = value;
mBuilder.delete(0, mBuilder.length());
mFmt.format("%02d", mArgs);
return mFmt.toString();
}
private static char getZeroDigit(Locale locale) {
return LocaleData.get(locale).zeroDigit;
}
private java.util.Formatter createFormatter(Locale locale) {
return new java.util.Formatter(mBuilder, locale);
}
}
private static final TwoDigitFormatter sTwoDigitFormatter = new TwoDigitFormatter();
/**
* @hide
*/
public static final Formatter getTwoDigitFormatter() {
return sTwoDigitFormatter;
}
/**
* The increment button.
*/
private final ImageButton mIncrementButton;
/**
* The decrement button.
*/
private final ImageButton mDecrementButton;
/**
* The text for showing the current value.
*/
private final EditText mInputText;
/**
* The distance between the two selection dividers.
*/
private final int mSelectionDividersDistance;
/**
* The min height of this widget.
*/
private final int mMinHeight;
/**
* The max height of this widget.
*/
private final int mMaxHeight;
/**
* The max width of this widget.
*/
private final int mMinWidth;
/**
* The max width of this widget.
*/
private int mMaxWidth;
/**
* Flag whether to compute the max width.
*/
private final boolean mComputeMaxWidth;
/**
* The height of the text.
*/
private final int mTextSize;
/**
* The height of the gap between text elements if the selector wheel.
*/
private int mSelectorTextGapHeight;
/**
* The values to be displayed instead the indices.
*/
private String[] mDisplayedValues;
/**
* Lower value of the range of numbers allowed for the NumberPicker
*/
private int mMinValue;
/**
* Upper value of the range of numbers allowed for the NumberPicker
*/
private int mMaxValue;
/**
* Current value of this NumberPicker
*/
private int mValue;
/**
* Listener to be notified upon current value change.
*/
private OnValueChangeListener mOnValueChangeListener;
/**
* Listener to be notified upon scroll state change.
*/
private OnScrollListener mOnScrollListener;
/**
* Formatter for for displaying the current value.
*/
private Formatter mFormatter;
/**
* The speed for updating the value form long press.
*/
private long mLongPressUpdateInterval = DEFAULT_LONG_PRESS_UPDATE_INTERVAL;
/**
* Cache for the string representation of selector indices.
*/
private final SparseArray<String> mSelectorIndexToStringCache = new SparseArray<String>();
/**
* The selector indices whose value are show by the selector.
*/
private final int[] mSelectorIndices = new int[SELECTOR_WHEEL_ITEM_COUNT];
/**
* The {@link Paint} for drawing the selector.
*/
private final Paint mSelectorWheelPaint;
/**
* The {@link Drawable} for pressed virtual (increment/decrement) buttons.
*/
private final Drawable mVirtualButtonPressedDrawable;
/**
* The height of a selector element (text + gap).
*/
private int mSelectorElementHeight;
/**
* The initial offset of the scroll selector.
*/
private int mInitialScrollOffset = Integer.MIN_VALUE;
/**
* The current offset of the scroll selector.
*/
private int mCurrentScrollOffset;
/**
* The {@link Scroller} responsible for flinging the selector.
*/
private final Scroller mFlingScroller;
/**
* The {@link Scroller} responsible for adjusting the selector.
*/
private final Scroller mAdjustScroller;
/**
* The previous Y coordinate while scrolling the selector.
*/
private int mPreviousScrollerY;
/**
* Handle to the reusable command for setting the input text selection.
*/
private SetSelectionCommand mSetSelectionCommand;
/**
* Handle to the reusable command for changing the current value from long
* press by one.
*/
private ChangeCurrentByOneFromLongPressCommand mChangeCurrentByOneFromLongPressCommand;
/**
* Command for beginning an edit of the current value via IME on long press.
*/
private BeginSoftInputOnLongPressCommand mBeginSoftInputOnLongPressCommand;
/**
* The Y position of the last down event.
*/
private float mLastDownEventY;
/**
* The time of the last down event.
*/
private long mLastDownEventTime;
/**
* The Y position of the last down or move event.
*/
private float mLastDownOrMoveEventY;
/**
* Determines speed during touch scrolling.
*/
private VelocityTracker mVelocityTracker;
/**
* @see ViewConfiguration#getScaledTouchSlop()
*/
private int mTouchSlop;
/**
* @see ViewConfiguration#getScaledMinimumFlingVelocity()
*/
private int mMinimumFlingVelocity;
/**
* @see ViewConfiguration#getScaledMaximumFlingVelocity()
*/
private int mMaximumFlingVelocity;
/**
* Flag whether the selector should wrap around.
*/
private boolean mWrapSelectorWheel;
/**
* The back ground color used to optimize scroller fading.
*/
private final int mSolidColor;
/**
* Flag whether this widget has a selector wheel.
*/
private final boolean mHasSelectorWheel;
/**
* Divider for showing item to be selected while scrolling
*/
private final Drawable mSelectionDivider;
/**
* The height of the selection divider.
*/
private final int mSelectionDividerHeight;
/**
* The current scroll state of the number picker.
*/
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
/**
* Flag whether to ignore move events - we ignore such when we show in IME
* to prevent the content from scrolling.
*/
private boolean mIgnoreMoveEvents;
/**
* Flag whether to perform a click on tap.
*/
private boolean mPerformClickOnTap;
/**
* The top of the top selection divider.
*/
private int mTopSelectionDividerTop;
/**
* The bottom of the bottom selection divider.
*/
private int mBottomSelectionDividerBottom;
/**
* The virtual id of the last hovered child.
*/
private int mLastHoveredChildVirtualViewId;
/**
* Whether the increment virtual button is pressed.
*/
private boolean mIncrementVirtualButtonPressed;
/**
* Whether the decrement virtual button is pressed.
*/
private boolean mDecrementVirtualButtonPressed;
/**
* Provider to report to clients the semantic structure of this widget.
*/
private AccessibilityNodeProviderImpl mAccessibilityNodeProvider;
/**
* Helper class for managing pressed state of the virtual buttons.
*/
private final PressedStateHelper mPressedStateHelper;
/**
* The keycode of the last handled DPAD down event.
*/
private int mLastHandledDownDpadKeyCode = -1;
/**
* If true then the selector wheel is hidden until the picker has focus.
*/
private boolean mHideWheelUntilFocused;
/**
* Interface to listen for changes of the current value.
*/
public interface OnValueChangeListener {
/**
* Called upon a change of the current value.
*
* @param picker The NumberPicker associated with this listener.
* @param oldVal The previous value.
* @param newVal The new value.
*/
void onValueChange(NumberPicker picker, int oldVal, int newVal);
}
/**
* Interface to listen for the picker scroll state.
*/
public interface OnScrollListener {
/** @hide */
@IntDef({SCROLL_STATE_IDLE, SCROLL_STATE_TOUCH_SCROLL, SCROLL_STATE_FLING})
@Retention(RetentionPolicy.SOURCE)
public @interface ScrollState {}
/**
* The view is not scrolling.
*/
public static int SCROLL_STATE_IDLE = 0;
/**
* The user is scrolling using touch, and his finger is still on the screen.
*/
public static int SCROLL_STATE_TOUCH_SCROLL = 1;
/**
* The user had previously been scrolling using touch and performed a fling.
*/
public static int SCROLL_STATE_FLING = 2;
/**
* Callback invoked while the number picker scroll state has changed.
*
* @param view The view whose scroll state is being reported.
* @param scrollState The current scroll state. One of
* {@link #SCROLL_STATE_IDLE},
* {@link #SCROLL_STATE_TOUCH_SCROLL} or
* {@link #SCROLL_STATE_IDLE}.
*/
public void onScrollStateChange(NumberPicker view, @ScrollState int scrollState);
}
/**
* Interface used to format current value into a string for presentation.
*/
public interface Formatter {
/**
* Formats a string representation of the current value.
*
* @param value The currently selected value.
* @return A formatted string representation.
*/
public String format(int value);
}
/**
* Create a new number picker.
*
* @param context The application environment.
*/
public NumberPicker(Context context) {
this(context, null);
}
/**
* Create a new number picker.
*
* @param context The application environment.
* @param attrs A collection of attributes.
*/
public NumberPicker(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.numberPickerStyle);
}
/**
* Create a new number picker
*
* @param context the application environment.
* @param attrs a collection of attributes.
* @param defStyleAttr An attribute in the current theme that contains a
* reference to a style resource that supplies default values for
* the view. Can be 0 to not look for defaults.
*/
public NumberPicker(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
/**
* Create a new number picker
*
* @param context the application environment.
* @param attrs a collection of attributes.
* @param defStyleAttr An attribute in the current theme that contains a
* reference to a style resource that supplies default values for
* the view. Can be 0 to not look for defaults.
* @param defStyleRes A resource identifier of a style resource that
* supplies default values for the view, used only if
* defStyleAttr is 0 or can not be found in the theme. Can be 0
* to not look for defaults.
*/
public NumberPicker(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
// process style attributes
final TypedArray attributesArray = context.obtainStyledAttributes(
attrs, R.styleable.NumberPicker, defStyleAttr, defStyleRes);
final int layoutResId = attributesArray.getResourceId(
R.styleable.NumberPicker_internalLayout, DEFAULT_LAYOUT_RESOURCE_ID);
mHasSelectorWheel = (layoutResId != DEFAULT_LAYOUT_RESOURCE_ID);
mHideWheelUntilFocused = attributesArray.getBoolean(
R.styleable.NumberPicker_hideWheelUntilFocused, false);
mSolidColor = attributesArray.getColor(R.styleable.NumberPicker_solidColor, 0);
final Drawable selectionDivider = attributesArray.getDrawable(
R.styleable.NumberPicker_selectionDivider);
if (selectionDivider != null) {
selectionDivider.setCallback(this);
selectionDivider.setLayoutDirection(getLayoutDirection());
if (selectionDivider.isStateful()) {
selectionDivider.setState(getDrawableState());
}
}
mSelectionDivider = selectionDivider;
final int defSelectionDividerHeight = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, UNSCALED_DEFAULT_SELECTION_DIVIDER_HEIGHT,
getResources().getDisplayMetrics());
mSelectionDividerHeight = attributesArray.getDimensionPixelSize(
R.styleable.NumberPicker_selectionDividerHeight, defSelectionDividerHeight);
final int defSelectionDividerDistance = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, UNSCALED_DEFAULT_SELECTION_DIVIDERS_DISTANCE,
getResources().getDisplayMetrics());
mSelectionDividersDistance = attributesArray.getDimensionPixelSize(
R.styleable.NumberPicker_selectionDividersDistance, defSelectionDividerDistance);
mMinHeight = attributesArray.getDimensionPixelSize(
R.styleable.NumberPicker_internalMinHeight, SIZE_UNSPECIFIED);
mMaxHeight = attributesArray.getDimensionPixelSize(
R.styleable.NumberPicker_internalMaxHeight, SIZE_UNSPECIFIED);
if (mMinHeight != SIZE_UNSPECIFIED && mMaxHeight != SIZE_UNSPECIFIED
&& mMinHeight > mMaxHeight) {
throw new IllegalArgumentException("minHeight > maxHeight");
}
mMinWidth = attributesArray.getDimensionPixelSize(
R.styleable.NumberPicker_internalMinWidth, SIZE_UNSPECIFIED);
mMaxWidth = attributesArray.getDimensionPixelSize(
R.styleable.NumberPicker_internalMaxWidth, SIZE_UNSPECIFIED);
if (mMinWidth != SIZE_UNSPECIFIED && mMaxWidth != SIZE_UNSPECIFIED
&& mMinWidth > mMaxWidth) {
throw new IllegalArgumentException("minWidth > maxWidth");
}
mComputeMaxWidth = (mMaxWidth == SIZE_UNSPECIFIED);
mVirtualButtonPressedDrawable = attributesArray.getDrawable(
R.styleable.NumberPicker_virtualButtonPressedDrawable);
attributesArray.recycle();
mPressedStateHelper = new PressedStateHelper();
// By default Linearlayout that we extend is not drawn. This is
// its draw() method is not called but dispatchDraw() is called
// directly (see ViewGroup.drawChild()). However, this class uses
// the fading edge effect implemented by View and we need our
// draw() method to be called. Therefore, we declare we will draw.
setWillNotDraw(!mHasSelectorWheel);
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(layoutResId, this, true);
OnClickListener onClickListener = new OnClickListener() {
public void onClick(View v) {
hideSoftInput();
mInputText.clearFocus();
if (v.getId() == R.id.increment) {
changeValueByOne(true);
} else {
changeValueByOne(false);
}
}
};
OnLongClickListener onLongClickListener = new OnLongClickListener() {
public boolean onLongClick(View v) {
hideSoftInput();
mInputText.clearFocus();
if (v.getId() == R.id.increment) {
postChangeCurrentByOneFromLongPress(true, 0);
} else {
postChangeCurrentByOneFromLongPress(false, 0);
}
return true;
}
};
// increment button
if (!mHasSelectorWheel) {
mIncrementButton = (ImageButton) findViewById(R.id.increment);
mIncrementButton.setOnClickListener(onClickListener);
mIncrementButton.setOnLongClickListener(onLongClickListener);
} else {
mIncrementButton = null;
}
// decrement button
if (!mHasSelectorWheel) {
mDecrementButton = (ImageButton) findViewById(R.id.decrement);
mDecrementButton.setOnClickListener(onClickListener);
mDecrementButton.setOnLongClickListener(onLongClickListener);
} else {
mDecrementButton = null;
}
// input text
mInputText = (EditText) findViewById(R.id.numberpicker_input);
mInputText.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
mInputText.selectAll();
} else {
mInputText.setSelection(0, 0);
validateInputTextView(v);
}
}
});
mInputText.setFilters(new InputFilter[] {
new InputTextFilter()
});
mInputText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
mInputText.setImeOptions(EditorInfo.IME_ACTION_DONE);
// initialize constants
ViewConfiguration configuration = ViewConfiguration.get(context);
mTouchSlop = configuration.getScaledTouchSlop();
mMinimumFlingVelocity = configuration.getScaledMinimumFlingVelocity();
mMaximumFlingVelocity = configuration.getScaledMaximumFlingVelocity()
/ SELECTOR_MAX_FLING_VELOCITY_ADJUSTMENT;
mTextSize = (int) mInputText.getTextSize();
// create the selector wheel paint
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setTextAlign(Align.CENTER);
paint.setTextSize(mTextSize);
paint.setTypeface(mInputText.getTypeface());
ColorStateList colors = mInputText.getTextColors();
int color = colors.getColorForState(ENABLED_STATE_SET, Color.WHITE);
paint.setColor(color);
mSelectorWheelPaint = paint;
// create the fling and adjust scrollers
mFlingScroller = new Scroller(getContext(), null, true);
mAdjustScroller = new Scroller(getContext(), new DecelerateInterpolator(2.5f));
updateInputTextView();
// If not explicitly specified this view is important for accessibility.
if (getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (!mHasSelectorWheel) {
super.onLayout(changed, left, top, right, bottom);
return;
}
final int msrdWdth = getMeasuredWidth();
final int msrdHght = getMeasuredHeight();
// Input text centered horizontally.
final int inptTxtMsrdWdth = mInputText.getMeasuredWidth();
final int inptTxtMsrdHght = mInputText.getMeasuredHeight();
final int inptTxtLeft = (msrdWdth - inptTxtMsrdWdth) / 2;
final int inptTxtTop = (msrdHght - inptTxtMsrdHght) / 2;
final int inptTxtRight = inptTxtLeft + inptTxtMsrdWdth;
final int inptTxtBottom = inptTxtTop + inptTxtMsrdHght;
mInputText.layout(inptTxtLeft, inptTxtTop, inptTxtRight, inptTxtBottom);
if (changed) {
// need to do all this when we know our size
initializeSelectorWheel();
initializeFadingEdges();
mTopSelectionDividerTop = (getHeight() - mSelectionDividersDistance) / 2
- mSelectionDividerHeight;
mBottomSelectionDividerBottom = mTopSelectionDividerTop + 2 * mSelectionDividerHeight
+ mSelectionDividersDistance;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (!mHasSelectorWheel) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
// Try greedily to fit the max width and height.
final int newWidthMeasureSpec = makeMeasureSpec(widthMeasureSpec, mMaxWidth);
final int newHeightMeasureSpec = makeMeasureSpec(heightMeasureSpec, mMaxHeight);
super.onMeasure(newWidthMeasureSpec, newHeightMeasureSpec);
// Flag if we are measured with width or height less than the respective min.
final int widthSize = resolveSizeAndStateRespectingMinSize(mMinWidth, getMeasuredWidth(),
widthMeasureSpec);
final int heightSize = resolveSizeAndStateRespectingMinSize(mMinHeight, getMeasuredHeight(),
heightMeasureSpec);
setMeasuredDimension(widthSize, heightSize);
}
/**
* Move to the final position of a scroller. Ensures to force finish the scroller
* and if it is not at its final position a scroll of the selector wheel is
* performed to fast forward to the final position.
*
* @param scroller The scroller to whose final position to get.
* @return True of the a move was performed, i.e. the scroller was not in final position.
*/
private boolean moveToFinalScrollerPosition(Scroller scroller) {
scroller.forceFinished(true);
int amountToScroll = scroller.getFinalY() - scroller.getCurrY();
int futureScrollOffset = (mCurrentScrollOffset + amountToScroll) % mSelectorElementHeight;
int overshootAdjustment = mInitialScrollOffset - futureScrollOffset;
if (overshootAdjustment != 0) {
if (Math.abs(overshootAdjustment) > mSelectorElementHeight / 2) {
if (overshootAdjustment > 0) {
overshootAdjustment -= mSelectorElementHeight;
} else {
overshootAdjustment += mSelectorElementHeight;
}
}
amountToScroll += overshootAdjustment;
scrollBy(0, amountToScroll);
return true;
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (!mHasSelectorWheel || !isEnabled()) {
return false;
}
final int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_DOWN: {
removeAllCallbacks();
mInputText.setVisibility(View.INVISIBLE);
mLastDownOrMoveEventY = mLastDownEventY = event.getY();
mLastDownEventTime = event.getEventTime();
mIgnoreMoveEvents = false;
mPerformClickOnTap = false;
// Handle pressed state before any state change.
if (mLastDownEventY < mTopSelectionDividerTop) {
if (mScrollState == OnScrollListener.SCROLL_STATE_IDLE) {
mPressedStateHelper.buttonPressDelayed(
PressedStateHelper.BUTTON_DECREMENT);
}
} else if (mLastDownEventY > mBottomSelectionDividerBottom) {
if (mScrollState == OnScrollListener.SCROLL_STATE_IDLE) {
mPressedStateHelper.buttonPressDelayed(
PressedStateHelper.BUTTON_INCREMENT);
}
}
// Make sure we support flinging inside scrollables.
getParent().requestDisallowInterceptTouchEvent(true);
if (!mFlingScroller.isFinished()) {
mFlingScroller.forceFinished(true);
mAdjustScroller.forceFinished(true);
onScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
} else if (!mAdjustScroller.isFinished()) {
mFlingScroller.forceFinished(true);
mAdjustScroller.forceFinished(true);
} else if (mLastDownEventY < mTopSelectionDividerTop) {
hideSoftInput();
postChangeCurrentByOneFromLongPress(
false, ViewConfiguration.getLongPressTimeout());
} else if (mLastDownEventY > mBottomSelectionDividerBottom) {
hideSoftInput();
postChangeCurrentByOneFromLongPress(
true, ViewConfiguration.getLongPressTimeout());
} else {
mPerformClickOnTap = true;
postBeginSoftInputOnLongPressCommand();
}
return true;
}
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isEnabled() || !mHasSelectorWheel) {
return false;
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(event);
int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_MOVE: {
if (mIgnoreMoveEvents) {
break;
}
float currentMoveY = event.getY();
if (mScrollState != OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
int deltaDownY = (int) Math.abs(currentMoveY - mLastDownEventY);
if (deltaDownY > mTouchSlop) {
removeAllCallbacks();
onScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
}
} else {
int deltaMoveY = (int) ((currentMoveY - mLastDownOrMoveEventY));
scrollBy(0, deltaMoveY);
invalidate();
}
mLastDownOrMoveEventY = currentMoveY;
} break;
case MotionEvent.ACTION_UP: {
removeBeginSoftInputCommand();
removeChangeCurrentByOneFromLongPress();
mPressedStateHelper.cancel();
VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity);
int initialVelocity = (int) velocityTracker.getYVelocity();
if (Math.abs(initialVelocity) > mMinimumFlingVelocity) {
fling(initialVelocity);
onScrollStateChange(OnScrollListener.SCROLL_STATE_FLING);
} else {
int eventY = (int) event.getY();
int deltaMoveY = (int) Math.abs(eventY - mLastDownEventY);
long deltaTime = event.getEventTime() - mLastDownEventTime;
if (deltaMoveY <= mTouchSlop && deltaTime < ViewConfiguration.getTapTimeout()) {
if (mPerformClickOnTap) {
mPerformClickOnTap = false;
performClick();
} else {
int selectorIndexOffset = (eventY / mSelectorElementHeight)
- SELECTOR_MIDDLE_ITEM_INDEX;
if (selectorIndexOffset > 0) {
changeValueByOne(true);
mPressedStateHelper.buttonTapped(
PressedStateHelper.BUTTON_INCREMENT);
} else if (selectorIndexOffset < 0) {
changeValueByOne(false);
mPressedStateHelper.buttonTapped(
PressedStateHelper.BUTTON_DECREMENT);
}
}
} else {
ensureScrollWheelAdjusted();
}
onScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
} break;
}
return true;
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
final int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
removeAllCallbacks();
break;
}
return super.dispatchTouchEvent(event);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
final int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
removeAllCallbacks();
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_UP:
if (!mHasSelectorWheel) {
break;
}