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