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