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