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