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