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