TimePickerDialog.java revision b612bb9493d006667f767c59278f8d0925dbd9f6
1/*
2 * Copyright (C) 2013 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 com.android.datetimepicker.time;
18
19import android.animation.ObjectAnimator;
20import android.annotation.SuppressLint;
21import android.app.ActionBar.LayoutParams;
22import android.app.DialogFragment;
23import android.content.Context;
24import android.content.res.Resources;
25import android.os.Bundle;
26import android.util.Log;
27import android.view.KeyCharacterMap;
28import android.view.KeyEvent;
29import android.view.LayoutInflater;
30import android.view.View;
31import android.view.View.OnClickListener;
32import android.view.View.OnKeyListener;
33import android.view.ViewGroup;
34import android.view.Window;
35import android.widget.RelativeLayout;
36import android.widget.TextView;
37
38import com.android.datetimepicker.R;
39
40import com.android.datetimepicker.time.RadialPickerLayout.OnValueSelectedListener;
41import com.android.datetimepicker.Utils;
42
43import java.text.DateFormatSymbols;
44import java.util.ArrayList;
45import java.util.Locale;
46
47/**
48 * Dialog to set a time.
49 */
50public class TimePickerDialog extends DialogFragment implements OnValueSelectedListener{
51    private static final String TAG = "TimePickerDialog";
52
53    private static final String KEY_HOUR_OF_DAY = "hour_of_day";
54    private static final String KEY_MINUTE = "minute";
55    private static final String KEY_IS_24_HOUR_VIEW = "is_24_hour_view";
56    private static final String KEY_CURRENT_ITEM_SHOWING = "current_item_showing";
57    private static final String KEY_IN_KB_MODE = "in_kb_mode";
58    private static final String KEY_TYPED_TIMES = "typed_times";
59
60    public static final int HOUR_INDEX = 0;
61    public static final int MINUTE_INDEX = 1;
62    // NOT a real index for the purpose of what's showing.
63    public static final int AMPM_INDEX = 2;
64    // Also NOT a real index, just used for keyboard mode.
65    public static final int ENABLE_PICKER_INDEX = 3;
66    public static final int AM = 0;
67    public static final int PM = 1;
68
69    // Delay before starting the pulse animation, in ms.
70    private static final int PULSE_ANIMATOR_DELAY = 300;
71
72    private OnTimeSetListener mCallback;
73
74    private TextView mDoneButton;
75    private TextView mHourView;
76    private TextView mHourSpaceView;
77    private TextView mMinuteView;
78    private TextView mMinuteSpaceView;
79    private TextView mAmPmTextView;
80    private View mAmPmHitspace;
81    private RadialPickerLayout mTimePicker;
82
83    private int mBlue;
84    private int mBlack;
85    private String mAmText;
86    private String mPmText;
87
88    private boolean mAllowAutoAdvance;
89    private int mInitialHourOfDay;
90    private int mInitialMinute;
91    private boolean mIs24HourMode;
92
93    // For hardware IME input.
94    private char mPlaceholderText;
95    private String mDoublePlaceholderText;
96    private boolean mInKbMode;
97    private ArrayList<Integer> mTypedTimes;
98    private Node mLegalTimesTree;
99    private int mAmKeyCode;
100    private int mPmKeyCode;
101
102    // Accessibility strings.
103    private String mHourPickerDescription;
104    private String mSelectHours;
105    private String mMinutePickerDescription;
106    private String mSelectMinutes;
107
108    /**
109     * The callback interface used to indicate the user is done filling in
110     * the time (they clicked on the 'Set' button).
111     */
112    public interface OnTimeSetListener {
113
114        /**
115         * @param view The view associated with this listener.
116         * @param hourOfDay The hour that was set.
117         * @param minute The minute that was set.
118         */
119        void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute);
120    }
121
122    public TimePickerDialog() {
123        // Empty constructor required for dialog fragment.
124    }
125
126    public TimePickerDialog(Context context, int theme, OnTimeSetListener callback,
127            int hourOfDay, int minute, boolean is24HourMode) {
128        // Empty constructor required for dialog fragment.
129    }
130
131    public static TimePickerDialog newInstance(OnTimeSetListener callback,
132            int hourOfDay, int minute, boolean is24HourMode) {
133        TimePickerDialog ret = new TimePickerDialog();
134        ret.initialize(callback, hourOfDay, minute, is24HourMode);
135        return ret;
136    }
137
138    public void initialize(OnTimeSetListener callback,
139            int hourOfDay, int minute, boolean is24HourMode) {
140        mCallback = callback;
141
142        mInitialHourOfDay = hourOfDay;
143        mInitialMinute = minute;
144        mIs24HourMode = is24HourMode;
145        mInKbMode = false;
146    }
147
148    public void setOnTimeSetListener(OnTimeSetListener callback) {
149        mCallback = callback;
150    }
151
152    public void setStartTime(int hourOfDay, int minute) {
153        mInitialHourOfDay = hourOfDay;
154        mInitialMinute = minute;
155        mInKbMode = false;
156    }
157
158    @Override
159    public void onCreate(Bundle savedInstanceState) {
160        super.onCreate(savedInstanceState);
161        if (savedInstanceState != null && savedInstanceState.containsKey(KEY_HOUR_OF_DAY)
162                    && savedInstanceState.containsKey(KEY_MINUTE)
163                    && savedInstanceState.containsKey(KEY_IS_24_HOUR_VIEW)) {
164            mInitialHourOfDay = savedInstanceState.getInt(KEY_HOUR_OF_DAY);
165            mInitialMinute = savedInstanceState.getInt(KEY_MINUTE);
166            mIs24HourMode = savedInstanceState.getBoolean(KEY_IS_24_HOUR_VIEW);
167            mInKbMode = savedInstanceState.getBoolean(KEY_IN_KB_MODE);
168        }
169    }
170
171    @Override
172    public View onCreateView(LayoutInflater inflater, ViewGroup container,
173            Bundle savedInstanceState) {
174        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
175
176        View view = inflater.inflate(R.layout.time_picker_dialog, null);
177        KeyboardListener keyboardListener = new KeyboardListener();
178        view.findViewById(R.id.time_picker_dialog).setOnKeyListener(keyboardListener);
179
180        Resources res = getResources();
181        mHourPickerDescription = res.getString(R.string.hour_picker_description);
182        mSelectHours = res.getString(R.string.select_hours);
183        mMinutePickerDescription = res.getString(R.string.minute_picker_description);
184        mSelectMinutes = res.getString(R.string.select_minutes);
185        mBlue = res.getColor(R.color.blue);
186        mBlack = res.getColor(R.color.numbers_text_color);
187
188        mHourView = (TextView) view.findViewById(R.id.hours);
189        mHourView.setOnKeyListener(keyboardListener);
190        mHourSpaceView = (TextView) view.findViewById(R.id.hour_space);
191        mMinuteSpaceView = (TextView) view.findViewById(R.id.minutes_space);
192        mMinuteView = (TextView) view.findViewById(R.id.minutes);
193        mMinuteView.setOnKeyListener(keyboardListener);
194        mAmPmTextView = (TextView) view.findViewById(R.id.ampm_label);
195        mAmPmTextView.setOnKeyListener(keyboardListener);
196        String[] amPmTexts = new DateFormatSymbols().getAmPmStrings();
197        mAmText = amPmTexts[0];
198        mPmText = amPmTexts[1];
199
200        mTimePicker = (RadialPickerLayout) view.findViewById(R.id.time_picker);
201        mTimePicker.setOnValueSelectedListener(this);
202        mTimePicker.setOnKeyListener(keyboardListener);
203        mTimePicker.initialize(getActivity(), mInitialHourOfDay, mInitialMinute, mIs24HourMode);
204        int currentItemShowing = HOUR_INDEX;
205        if (savedInstanceState != null &&
206                savedInstanceState.containsKey(KEY_CURRENT_ITEM_SHOWING)) {
207            currentItemShowing = savedInstanceState.getInt(KEY_CURRENT_ITEM_SHOWING);
208        }
209        setCurrentItemShowing(currentItemShowing, false, true, true);
210        mTimePicker.invalidate();
211
212        mHourView.setOnClickListener(new OnClickListener() {
213            @Override
214            public void onClick(View v) {
215                setCurrentItemShowing(HOUR_INDEX, true, false, true);
216                mTimePicker.tryVibrate();
217            }
218        });
219        mMinuteView.setOnClickListener(new OnClickListener() {
220            @Override
221            public void onClick(View v) {
222                setCurrentItemShowing(MINUTE_INDEX, true, false, true);
223                mTimePicker.tryVibrate();
224            }
225        });
226
227        mDoneButton = (TextView) view.findViewById(R.id.done_button);
228        mDoneButton.setOnClickListener(new OnClickListener() {
229            @Override
230            public void onClick(View v) {
231                if (mInKbMode && isTypedTimeFullyLegal()) {
232                    finishKbMode(false);
233                } else {
234                    mTimePicker.tryVibrate();
235                }
236                if (mCallback != null) {
237                    mCallback.onTimeSet(mTimePicker,
238                            mTimePicker.getHours(), mTimePicker.getMinutes());
239                }
240                dismiss();
241            }
242        });
243        mDoneButton.setOnKeyListener(keyboardListener);
244
245        // Enable or disable the AM/PM view.
246        mAmPmHitspace = view.findViewById(R.id.ampm_hitspace);
247        if (mIs24HourMode) {
248            mAmPmTextView.setVisibility(View.GONE);
249
250            RelativeLayout.LayoutParams paramsSeparator = new RelativeLayout.LayoutParams(
251                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
252            paramsSeparator.addRule(RelativeLayout.CENTER_IN_PARENT);
253            TextView separatorView = (TextView) view.findViewById(R.id.separator);
254            separatorView.setLayoutParams(paramsSeparator);
255        } else {
256            mAmPmTextView.setVisibility(View.VISIBLE);
257            updateAmPmDisplay(mInitialHourOfDay < 12? AM : PM);
258            mAmPmHitspace.setOnClickListener(new OnClickListener() {
259                @Override
260                public void onClick(View v) {
261                    mTimePicker.tryVibrate();
262                    int amOrPm = mTimePicker.getIsCurrentlyAmOrPm();
263                    if (amOrPm == AM) {
264                        amOrPm = PM;
265                    } else if (amOrPm == PM){
266                        amOrPm = AM;
267                    }
268                    updateAmPmDisplay(amOrPm);
269                    mTimePicker.setAmOrPm(amOrPm);
270                }
271            });
272        }
273
274        mAllowAutoAdvance = true;
275        setHour(mInitialHourOfDay, true);
276        setMinute(mInitialMinute);
277
278        // Set up for keyboard mode.
279        mDoublePlaceholderText = res.getString(R.string.time_placeholder);
280        mPlaceholderText = mDoublePlaceholderText.charAt(0);
281        mAmKeyCode = mPmKeyCode = -1;
282        generateLegalTimesTree();
283        if (mInKbMode) {
284            mTypedTimes = savedInstanceState.getIntegerArrayList(KEY_TYPED_TIMES);
285            tryStartingKbMode(-1);
286            mHourView.invalidate();
287        } else if (mTypedTimes == null) {
288            mTypedTimes = new ArrayList<Integer>();
289        }
290
291        return view;
292    }
293
294    private void updateAmPmDisplay(int amOrPm) {
295        if (amOrPm == AM) {
296            mAmPmTextView.setText(mAmText);
297            tryAccessibilityAnnounce(mAmText);
298            mAmPmHitspace.setContentDescription(mAmText);
299        } else if (amOrPm == PM){
300            mAmPmTextView.setText(mPmText);
301            tryAccessibilityAnnounce(mPmText);
302            mAmPmHitspace.setContentDescription(mPmText);
303        } else {
304            mAmPmTextView.setText(mDoublePlaceholderText);
305        }
306    }
307
308    @Override
309    public void onSaveInstanceState(Bundle outState) {
310        if (mTimePicker != null) {
311            outState.putInt(KEY_HOUR_OF_DAY, mTimePicker.getHours());
312            outState.putInt(KEY_MINUTE, mTimePicker.getMinutes());
313            outState.putBoolean(KEY_IS_24_HOUR_VIEW, mIs24HourMode);
314            outState.putInt(KEY_CURRENT_ITEM_SHOWING, mTimePicker.getCurrentItemShowing());
315            outState.putBoolean(KEY_IN_KB_MODE, mInKbMode);
316            if (mInKbMode) {
317                outState.putIntegerArrayList(KEY_TYPED_TIMES, mTypedTimes);
318            }
319        }
320    }
321
322    /**
323     * Called by the picker for updating the header display.
324     */
325    @Override
326    public void onValueSelected(int pickerIndex, int newValue, boolean autoAdvance) {
327        if (pickerIndex == HOUR_INDEX) {
328            setHour(newValue, false);
329            String announcement = String.format("%d", newValue);
330            if (mAllowAutoAdvance && autoAdvance) {
331                setCurrentItemShowing(MINUTE_INDEX, true, true, false);
332                announcement += ". " + mSelectMinutes;
333            }
334            tryAccessibilityAnnounce(announcement);
335        } else if (pickerIndex == MINUTE_INDEX){
336            setMinute(newValue);
337        } else if (pickerIndex == AMPM_INDEX) {
338            updateAmPmDisplay(newValue);
339        } else if (pickerIndex == ENABLE_PICKER_INDEX) {
340            if (!isTypedTimeFullyLegal()) {
341                mTypedTimes.clear();
342            }
343            finishKbMode(true);
344        }
345    }
346
347    private void setHour(int value, boolean announce) {
348        String format;
349        if (mIs24HourMode) {
350            format = "%02d";
351        } else {
352            format = "%d";
353            value = value % 12;
354            if (value == 0) {
355                value = 12;
356            }
357        }
358
359        CharSequence text = String.format(format, value);
360        mHourView.setText(text);
361        mHourSpaceView.setText(text);
362        if (announce) {
363            tryAccessibilityAnnounce(text);
364        }
365    }
366
367    private void setMinute(int value) {
368        if (value == 60) {
369            value = 0;
370        }
371        CharSequence text = String.format(Locale.getDefault(), "%02d", value);
372        tryAccessibilityAnnounce(text);
373        mMinuteView.setText(text);
374        mMinuteSpaceView.setText(text);
375    }
376
377    // Show either Hours or Minutes.
378    private void setCurrentItemShowing(int index, boolean animateCircle, boolean delayLabelAnimate,
379            boolean announce) {
380        mTimePicker.setCurrentItemShowing(index, animateCircle);
381
382        TextView labelToAnimate;
383        if (index == HOUR_INDEX) {
384            int hours = mTimePicker.getHours();
385            if (!mIs24HourMode) {
386                hours = hours % 12;
387            }
388            mTimePicker.setContentDescription(mHourPickerDescription+": "+hours);
389            if (announce) {
390                tryAccessibilityAnnounce(mSelectHours);
391            }
392            labelToAnimate = mHourView;
393        } else {
394            int minutes = mTimePicker.getMinutes();
395            mTimePicker.setContentDescription(mMinutePickerDescription+": "+minutes);
396            if (announce) {
397                tryAccessibilityAnnounce(mSelectMinutes);
398            }
399            labelToAnimate = mMinuteView;
400        }
401
402        int hourColor = (index == HOUR_INDEX)? mBlue : mBlack;
403        int minuteColor = (index == MINUTE_INDEX)? mBlue : mBlack;
404        mHourView.setTextColor(hourColor);
405        mMinuteView.setTextColor(minuteColor);
406
407        ObjectAnimator pulseAnimator = Utils.getPulseAnimator(labelToAnimate);
408        if (delayLabelAnimate) {
409            pulseAnimator.setStartDelay(PULSE_ANIMATOR_DELAY);
410        }
411        pulseAnimator.start();
412    }
413
414    /**
415     * Try to speak the specified text, for accessibility. Only available on JB or later.
416     * @param text
417     */
418    @SuppressLint("NewApi")
419    private void tryAccessibilityAnnounce(CharSequence text) {
420        if (Utils.isJellybeanOrLater() && mTimePicker != null && text != null) {
421            mTimePicker.announceForAccessibility(text);
422        }
423    }
424
425    /**
426     * For keyboard mode, processes key events.
427     * @param keyCode the pressed key.
428     * @return true if the key was successfully processed, false otherwise.
429     */
430    private boolean processKeyUp(int keyCode) {
431        if (keyCode == KeyEvent.KEYCODE_ESCAPE || keyCode == KeyEvent.KEYCODE_BACK) {
432            dismiss();
433            return true;
434        } else if (keyCode == KeyEvent.KEYCODE_TAB) {
435            if(mInKbMode) {
436                if (isTypedTimeFullyLegal()) {
437                    finishKbMode(true);
438                }
439                return true;
440            }
441        } else if (keyCode == KeyEvent.KEYCODE_ENTER) {
442            if (mInKbMode) {
443                if (!isTypedTimeFullyLegal()) {
444                    return true;
445                }
446                finishKbMode(false);
447            }
448            if (mCallback != null) {
449                mCallback.onTimeSet(mTimePicker,
450                        mTimePicker.getHours(), mTimePicker.getMinutes());
451            }
452            dismiss();
453            return true;
454        } else if (keyCode == KeyEvent.KEYCODE_DEL) {
455            if (mInKbMode) {
456                if (!mTypedTimes.isEmpty()) {
457                    deleteLastTypedKey();
458                    updateDisplay(true);
459                }
460            }
461        } else if (keyCode == KeyEvent.KEYCODE_0 || keyCode == KeyEvent.KEYCODE_1
462                || keyCode == KeyEvent.KEYCODE_2 || keyCode == KeyEvent.KEYCODE_3
463                || keyCode == KeyEvent.KEYCODE_4 || keyCode == KeyEvent.KEYCODE_5
464                || keyCode == KeyEvent.KEYCODE_6 || keyCode == KeyEvent.KEYCODE_7
465                || keyCode == KeyEvent.KEYCODE_8 || keyCode == KeyEvent.KEYCODE_9
466                || (!mIs24HourMode &&
467                        (keyCode == getAmOrPmKeyCode(AM) || keyCode == getAmOrPmKeyCode(PM)))) {
468            if (!mInKbMode) {
469                if (mTimePicker == null) {
470                    // Something's wrong, because time picker should definitely not be null.
471                    Log.e(TAG, "Unable to initiate keyboard mode, TimePicker was null.");
472                    return true;
473                }
474                mTypedTimes.clear();
475                tryStartingKbMode(keyCode);
476                return true;
477            }
478            // We're already in keyboard mode.
479            if (addKeyIfLegal(keyCode)) {
480                updateDisplay(false);
481            }
482            return true;
483        }
484        return false;
485    }
486
487    /**
488     * Try to start keyboard mode with the specified key, as long as the timepicker is not in the
489     * middle of a touch-event.
490     * @param keyCode The key to use as the first press. Keyboard mode will not be started if the
491     * key is not legal to start with. Or, pass in -1 to get into keyboard mode without a starting
492     * key.
493     */
494    private void tryStartingKbMode(int keyCode) {
495        if (mTimePicker.trySettingInputEnabled(false) &&
496                (keyCode == -1 || addKeyIfLegal(keyCode))) {
497            mInKbMode = true;
498            mDoneButton.setEnabled(false);
499            updateDisplay(false);
500        }
501    }
502
503    private boolean addKeyIfLegal(int keyCode) {
504        // If we're in 24hour mode, we'll need to check if the input is full. If in AM/PM mode,
505        // we'll need to see if AM/PM have been typed.
506        if ((mIs24HourMode && mTypedTimes.size() == 4) ||
507                (!mIs24HourMode && isTypedTimeFullyLegal())) {
508            return false;
509        }
510
511        mTypedTimes.add(keyCode);
512        if (!isTypedTimeLegalSoFar()) {
513            deleteLastTypedKey();
514            return false;
515        }
516
517        // Automatically fill in 0's if AM or PM was legally entered.
518        if (isTypedTimeFullyLegal()) {
519            if (!mIs24HourMode && mTypedTimes.size() <= 3) {
520                mTypedTimes.add(mTypedTimes.size() - 1, KeyEvent.KEYCODE_0);
521                mTypedTimes.add(mTypedTimes.size() - 1, KeyEvent.KEYCODE_0);
522            }
523            mDoneButton.setEnabled(true);
524        }
525
526        return true;
527    }
528
529    /**
530     * Traverse the tree to see if the keys that have been typed so far are legal as is,
531     * or may become legal as more keys are typed (excluding backspace).
532     */
533    private boolean isTypedTimeLegalSoFar() {
534        Node node = mLegalTimesTree;
535        for (int keyCode : mTypedTimes) {
536            node = node.canReach(keyCode);
537            if (node == null) {
538                return false;
539            }
540        }
541        return true;
542    }
543
544    /**
545     * Check if the time that has been typed so far is completely legal, as is.
546     */
547    private boolean isTypedTimeFullyLegal() {
548        if (mIs24HourMode) {
549            // For 24-hour mode, the time is legal if the hours and minutes are each legal. Note:
550            // getEnteredTime() will ONLY call isTypedTimeFullyLegal() when NOT in 24hour mode.
551            int[] values = getEnteredTime(null);
552            return (values[0] >= 0 && values[1] >= 0 && values[1] < 60);
553        } else {
554            // For AM/PM mode, the time is legal if it contains an AM or PM, as those can only be
555            // legally added at specific times based on the tree's algorithm.
556            return (mTypedTimes.contains(getAmOrPmKeyCode(AM)) ||
557                    mTypedTimes.contains(getAmOrPmKeyCode(PM)));
558        }
559    }
560
561    private void deleteLastTypedKey() {
562        mTypedTimes.remove(mTypedTimes.size() - 1);
563        if (!isTypedTimeFullyLegal()) {
564            mDoneButton.setEnabled(false);
565        }
566    }
567
568    /**
569     * Get out of keyboard mode. If there is nothing in typedTimes, revert to TimePicker's time.
570     * @param changeDisplays If true, update the displays with the relevant time.
571     */
572    private void finishKbMode(boolean updateDisplays) {
573        mInKbMode = false;
574        if (!mTypedTimes.isEmpty()) {
575            int values[] = getEnteredTime(null);
576            mTimePicker.setTime(values[0], values[1]);
577            if (!mIs24HourMode) {
578                mTimePicker.setAmOrPm(values[2]);
579            }
580            mTypedTimes.clear();
581        }
582        if (updateDisplays) {
583            updateDisplay(false);
584            mTimePicker.trySettingInputEnabled(true);
585        }
586    }
587
588    /**
589     * Update the hours, minutes, and AM/PM displays with the typed times. If the typedTimes is
590     * empty, either show an empty display (filled with the placeholder text), or update from the
591     * timepicker's values.
592     * @param allowEmptyDisplay if true, then if the typedTimes is empty, use the placeholder text.
593     * Otherwise, revert to the timepicker's values.
594     */
595    private void updateDisplay(boolean allowEmptyDisplay) {
596        if (!allowEmptyDisplay && mTypedTimes.isEmpty()) {
597            int hour = mTimePicker.getHours();
598            int minute = mTimePicker.getMinutes();
599            setHour(hour, true);
600            setMinute(minute);
601            if (!mIs24HourMode) {
602                updateAmPmDisplay(hour < 12? AM : PM);
603            }
604            setCurrentItemShowing(mTimePicker.getCurrentItemShowing(), true, true, true);
605            mDoneButton.setEnabled(true);
606        } else {
607            Boolean[] enteredZeros = {false, false};
608            int[] values = getEnteredTime(enteredZeros);
609            String hourFormat = enteredZeros[0]? "%02d" : "%2d";
610            String minuteFormat = (enteredZeros[1])? "%02d" : "%2d";
611            String hourStr = (values[0] == -1)? mDoublePlaceholderText :
612                String.format(hourFormat, values[0]).replace(' ', mPlaceholderText);
613            String minuteStr = (values[1] == -1)? mDoublePlaceholderText :
614                String.format(minuteFormat, values[1]).replace(' ', mPlaceholderText);
615            mHourView.setText(hourStr);
616            mHourView.setTextColor(mBlack);
617            mMinuteView.setText(minuteStr);
618            mMinuteView.setTextColor(mBlack);
619            if (!mIs24HourMode) {
620                updateAmPmDisplay(values[2]);
621            }
622        }
623    }
624
625    private int getValFromKeyCode(int keyCode) {
626        switch (keyCode) {
627            case KeyEvent.KEYCODE_0:
628                return 0;
629            case KeyEvent.KEYCODE_1:
630                return 1;
631            case KeyEvent.KEYCODE_2:
632                return 2;
633            case KeyEvent.KEYCODE_3:
634                return 3;
635            case KeyEvent.KEYCODE_4:
636                return 4;
637            case KeyEvent.KEYCODE_5:
638                return 5;
639            case KeyEvent.KEYCODE_6:
640                return 6;
641            case KeyEvent.KEYCODE_7:
642                return 7;
643            case KeyEvent.KEYCODE_8:
644                return 8;
645            case KeyEvent.KEYCODE_9:
646                return 9;
647            default:
648                return -1;
649        }
650    }
651
652    /**
653     * Get the currently-entered time, as integer values of the hours and minutes typed.
654     * @param enteredZeros A size-2 boolean array, which the caller should initialize, and which
655     * may then be used for the caller to know whether zeros had been explicitly entered as either
656     * hours of minutes. This is helpful for deciding whether to show the dashes, or actual 0's.
657     * @return A size-3 int array. The first value will be the hours, the second value will be the
658     * minutes, and the third will be either TimePickerDialog.AM or TimePickerDialog.PM.
659     */
660    private int[] getEnteredTime(Boolean[] enteredZeros) {
661        int amOrPm = -1;
662        int startIndex = 1;
663        if (!mIs24HourMode && isTypedTimeFullyLegal()) {
664            int keyCode = mTypedTimes.get(mTypedTimes.size() - 1);
665            if (keyCode == getAmOrPmKeyCode(AM)) {
666                amOrPm = AM;
667            } else if (keyCode == getAmOrPmKeyCode(PM)){
668                amOrPm = PM;
669            }
670            startIndex = 2;
671        }
672        int minute = -1;
673        int hour = -1;
674        for (int i = startIndex; i <= mTypedTimes.size(); i++) {
675            int val = getValFromKeyCode(mTypedTimes.get(mTypedTimes.size() - i));
676            if (i == startIndex) {
677                minute = val;
678            } else if (i == startIndex+1) {
679                minute += 10*val;
680                if (enteredZeros != null && val == 0) {
681                    enteredZeros[1] = true;
682                }
683            } else if (i == startIndex+2) {
684                hour = val;
685            } else if (i == startIndex+3) {
686                hour += 10*val;
687                if (enteredZeros != null && val == 0) {
688                    enteredZeros[0] = true;
689                }
690            }
691        }
692
693        int[] ret = {hour, minute, amOrPm};
694        return ret;
695    }
696
697    /**
698     * Get the keycode value for AM and PM in the current language.
699     */
700    private int getAmOrPmKeyCode(int amOrPm) {
701        // Cache the codes.
702        if (mAmKeyCode == -1 || mPmKeyCode == -1) {
703            // Find the first character in the AM/PM text that is unique.
704            KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
705            char amChar;
706            char pmChar;
707            for (int i = 0; i < Math.max(mAmText.length(), mPmText.length()); i++) {
708                amChar = mAmText.toLowerCase(Locale.getDefault()).charAt(i);
709                pmChar = mPmText.toLowerCase(Locale.getDefault()).charAt(i);
710                if (amChar != pmChar) {
711                    KeyEvent[] events = kcm.getEvents(new char[]{amChar, pmChar});
712                    // There should be 4 events: a down and up for both AM and PM.
713                    if (events != null && events.length == 4) {
714                        mAmKeyCode = events[0].getKeyCode();
715                        mPmKeyCode = events[2].getKeyCode();
716                    } else {
717                        Log.e(TAG, "Unable to find keycodes for AM and PM.");
718                    }
719                    break;
720                }
721            }
722        }
723        if (amOrPm == AM) {
724            return mAmKeyCode;
725        } else if (amOrPm == PM) {
726            return mPmKeyCode;
727        }
728
729        return -1;
730    }
731
732    /**
733     * Create a tree for deciding what keys can legally be typed.
734     */
735    private void generateLegalTimesTree() {
736        // Create a quick cache of numbers to their keycodes.
737        int k0 = KeyEvent.KEYCODE_0;
738        int k1 = KeyEvent.KEYCODE_1;
739        int k2 = KeyEvent.KEYCODE_2;
740        int k3 = KeyEvent.KEYCODE_3;
741        int k4 = KeyEvent.KEYCODE_4;
742        int k5 = KeyEvent.KEYCODE_5;
743        int k6 = KeyEvent.KEYCODE_6;
744        int k7 = KeyEvent.KEYCODE_7;
745        int k8 = KeyEvent.KEYCODE_8;
746        int k9 = KeyEvent.KEYCODE_9;
747
748        // The root of the tree doesn't contain any numbers.
749        mLegalTimesTree = new Node();
750        if (mIs24HourMode) {
751            // We'll be re-using these nodes, so we'll save them.
752            Node minuteFirstDigit = new Node(k0, k1, k2, k3, k4, k5);
753            Node minuteSecondDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
754            // The first digit must be followed by the second digit.
755            minuteFirstDigit.addChild(minuteSecondDigit);
756
757            // The first digit may be 0-1.
758            Node firstDigit = new Node(k0, k1);
759            mLegalTimesTree.addChild(firstDigit);
760
761            // When the first digit is 0-1, the second digit may be 0-5.
762            Node secondDigit = new Node(k0, k1, k2, k3, k4, k5);
763            firstDigit.addChild(secondDigit);
764            // We may now be followed by the first minute digit. E.g. 00:09, 15:58.
765            secondDigit.addChild(minuteFirstDigit);
766
767            // When the first digit is 0-1, and the second digit is 0-5, the third digit may be 6-9.
768            Node thirdDigit = new Node(k6, k7, k8, k9);
769            // The time must now be finished. E.g. 0:55, 1:08.
770            secondDigit.addChild(thirdDigit);
771
772            // When the first digit is 0-1, the second digit may be 6-9.
773            secondDigit = new Node(k6, k7, k8, k9);
774            firstDigit.addChild(secondDigit);
775            // We must now be followed by the first minute digit. E.g. 06:50, 18:20.
776            secondDigit.addChild(minuteFirstDigit);
777
778            // The first digit may be 2.
779            firstDigit = new Node(k2);
780            mLegalTimesTree.addChild(firstDigit);
781
782            // When the first digit is 2, the second digit may be 0-3.
783            secondDigit = new Node(k0, k1, k2, k3);
784            firstDigit.addChild(secondDigit);
785            // We must now be followed by the first minute digit. E.g. 20:50, 23:09.
786            secondDigit.addChild(minuteFirstDigit);
787
788            // When the first digit is 2, the second digit may be 4-5.
789            secondDigit = new Node(k4, k5);
790            firstDigit.addChild(secondDigit);
791            // We must now be followd by the last minute digit. E.g. 2:40, 2:53.
792            secondDigit.addChild(minuteSecondDigit);
793
794            // The first digit may be 3-9.
795            firstDigit = new Node(k3, k4, k5, k6, k7, k8, k9);
796            mLegalTimesTree.addChild(firstDigit);
797            // We must now be followed by the first minute digit. E.g. 3:57, 8:12.
798            firstDigit.addChild(minuteFirstDigit);
799        } else {
800            // We'll need to use the AM/PM node a lot.
801            // Set up AM and PM to respond to "a" and "p".
802            Node ampm = new Node(getAmOrPmKeyCode(AM), getAmOrPmKeyCode(PM));
803
804            // The first hour digit may be 1.
805            Node firstDigit = new Node(k1);
806            mLegalTimesTree.addChild(firstDigit);
807            // We'll allow quick input of on-the-hour times. E.g. 1pm.
808            firstDigit.addChild(ampm);
809
810            // When the first digit is 1, the second digit may be 0-2.
811            Node secondDigit = new Node(k0, k1, k2);
812            firstDigit.addChild(secondDigit);
813            // Also for quick input of on-the-hour times. E.g. 10pm, 12am.
814            secondDigit.addChild(ampm);
815
816            // When the first digit is 1, and the second digit is 0-2, the third digit may be 0-5.
817            Node thirdDigit = new Node(k0, k1, k2, k3, k4, k5);
818            secondDigit.addChild(thirdDigit);
819            // The time may be finished now. E.g. 1:02pm, 1:25am.
820            thirdDigit.addChild(ampm);
821
822            // When the first digit is 1, the second digit is 0-2, and the third digit is 0-5,
823            // the fourth digit may be 0-9.
824            Node fourthDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
825            thirdDigit.addChild(fourthDigit);
826            // The time must be finished now. E.g. 10:49am, 12:40pm.
827            fourthDigit.addChild(ampm);
828
829            // When the first digit is 1, and the second digit is 0-2, the third digit may be 6-9.
830            thirdDigit = new Node(k6, k7, k8, k9);
831            secondDigit.addChild(thirdDigit);
832            // The time must be finished now. E.g. 1:08am, 1:26pm.
833            thirdDigit.addChild(ampm);
834
835            // When the first digit is 1, the second digit may be 3-5.
836            secondDigit = new Node(k3, k4, k5);
837            firstDigit.addChild(secondDigit);
838
839            // When the first digit is 1, and the second digit is 3-5, the third digit may be 0-9.
840            thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
841            secondDigit.addChild(thirdDigit);
842            // The time must be finished now. E.g. 1:39am, 1:50pm.
843            thirdDigit.addChild(ampm);
844
845            // The hour digit may be 2-9.
846            firstDigit = new Node(k2, k3, k4, k5, k6, k7, k8, k9);
847            mLegalTimesTree.addChild(firstDigit);
848            // We'll allow quick input of on-the-hour-times. E.g. 2am, 5pm.
849            firstDigit.addChild(ampm);
850
851            // When the first digit is 2-9, the second digit may be 0-5.
852            secondDigit = new Node(k0, k1, k2, k3, k4, k5);
853            firstDigit.addChild(secondDigit);
854
855            // When the first digit is 2-9, and the second digit is 0-5, the third digit may be 0-9.
856            thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
857            secondDigit.addChild(thirdDigit);
858            // The time must be finished now. E.g. 2:57am, 9:30pm.
859            thirdDigit.addChild(ampm);
860        }
861    }
862
863    /**
864     * Simple node class to be used for traversal to check for legal times.
865     * mLegalKeys represents the keys that can be typed to get to the node.
866     * mChildren are the children that can be reached from this node.
867     */
868    private class Node {
869        private int[] mLegalKeys;
870        private ArrayList<Node> mChildren;
871
872        public Node(int... legalKeys) {
873            mLegalKeys = legalKeys;
874            mChildren = new ArrayList<Node>();
875        }
876
877        public void addChild(Node child) {
878            mChildren.add(child);
879        }
880
881        public boolean containsKey(int key) {
882            for (int i = 0; i < mLegalKeys.length; i++) {
883                if (mLegalKeys[i] == key) {
884                    return true;
885                }
886            }
887            return false;
888        }
889
890        public Node canReach(int key) {
891            if (mChildren == null) {
892                return null;
893            }
894            for (Node child : mChildren) {
895                if (child.containsKey(key)) {
896                    return child;
897                }
898            }
899            return null;
900        }
901    }
902
903    private class KeyboardListener implements OnKeyListener {
904        @Override
905        public boolean onKey(View v, int keyCode, KeyEvent event) {
906            if (event.getAction() == KeyEvent.ACTION_UP) {
907                return processKeyUp(keyCode);
908            }
909            return false;
910        }
911    }
912}
913