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