TimePickerDialog.java revision c9d330f99ce1f2a58012fe1c4f12bdad544ede52
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 } 334 Utils.tryAccessibilityAnnounce(mTimePicker, announcement); 335 } else if (pickerIndex == MINUTE_INDEX){ 336 setMinute(newValue); 337 } else if (pickerIndex == AMPM_INDEX) { 338 updateAmPmDisplay(newValue); 339 } else if (pickerIndex == ENABLE_PICKER_INDEX) { 340 if (!isTypedTimeFullyLegal()) { 341 mTypedTimes.clear(); 342 } 343 finishKbMode(true); 344 } 345 } 346 347 private void setHour(int value, boolean announce) { 348 String format; 349 if (mIs24HourMode) { 350 format = "%02d"; 351 } else { 352 format = "%d"; 353 value = value % 12; 354 if (value == 0) { 355 value = 12; 356 } 357 } 358 359 CharSequence text = String.format(format, value); 360 mHourView.setText(text); 361 mHourSpaceView.setText(text); 362 if (announce) { 363 Utils.tryAccessibilityAnnounce(mTimePicker, text); 364 } 365 } 366 367 private void setMinute(int value) { 368 if (value == 60) { 369 value = 0; 370 } 371 CharSequence text = String.format(Locale.getDefault(), "%02d", value); 372 Utils.tryAccessibilityAnnounce(mTimePicker, text); 373 mMinuteView.setText(text); 374 mMinuteSpaceView.setText(text); 375 } 376 377 // Show either Hours or Minutes. 378 private void setCurrentItemShowing(int index, boolean animateCircle, boolean delayLabelAnimate, 379 boolean announce) { 380 mTimePicker.setCurrentItemShowing(index, animateCircle); 381 382 TextView labelToAnimate; 383 if (index == HOUR_INDEX) { 384 int hours = mTimePicker.getHours(); 385 if (!mIs24HourMode) { 386 hours = hours % 12; 387 } 388 mTimePicker.setContentDescription(mHourPickerDescription+": "+hours); 389 if (announce) { 390 Utils.tryAccessibilityAnnounce(mTimePicker, mSelectHours); 391 } 392 labelToAnimate = mHourView; 393 } else { 394 int minutes = mTimePicker.getMinutes(); 395 mTimePicker.setContentDescription(mMinutePickerDescription+": "+minutes); 396 if (announce) { 397 Utils.tryAccessibilityAnnounce(mTimePicker, mSelectMinutes); 398 } 399 labelToAnimate = mMinuteView; 400 } 401 402 int hourColor = (index == HOUR_INDEX)? mBlue : mBlack; 403 int minuteColor = (index == MINUTE_INDEX)? mBlue : mBlack; 404 mHourView.setTextColor(hourColor); 405 mMinuteView.setTextColor(minuteColor); 406 407 ObjectAnimator pulseAnimator = Utils.getPulseAnimator(labelToAnimate, 0.85f, 1.1f); 408 if (delayLabelAnimate) { 409 pulseAnimator.setStartDelay(PULSE_ANIMATOR_DELAY); 410 } 411 pulseAnimator.start(); 412 } 413 414 /** 415 * For keyboard mode, processes key events. 416 * @param keyCode the pressed key. 417 * @return true if the key was successfully processed, false otherwise. 418 */ 419 private boolean processKeyUp(int keyCode) { 420 if (keyCode == KeyEvent.KEYCODE_ESCAPE || keyCode == KeyEvent.KEYCODE_BACK) { 421 dismiss(); 422 return true; 423 } else if (keyCode == KeyEvent.KEYCODE_TAB) { 424 if(mInKbMode) { 425 if (isTypedTimeFullyLegal()) { 426 finishKbMode(true); 427 } 428 return true; 429 } 430 } else if (keyCode == KeyEvent.KEYCODE_ENTER) { 431 if (mInKbMode) { 432 if (!isTypedTimeFullyLegal()) { 433 return true; 434 } 435 finishKbMode(false); 436 } 437 if (mCallback != null) { 438 mCallback.onTimeSet(mTimePicker, 439 mTimePicker.getHours(), mTimePicker.getMinutes()); 440 } 441 dismiss(); 442 return true; 443 } else if (keyCode == KeyEvent.KEYCODE_DEL) { 444 if (mInKbMode) { 445 if (!mTypedTimes.isEmpty()) { 446 int deleted = deleteLastTypedKey(); 447 String deletedKeyStr; 448 if (deleted == getAmOrPmKeyCode(AM)) { 449 deletedKeyStr = mAmText; 450 } else if (deleted == getAmOrPmKeyCode(PM)) { 451 deletedKeyStr = mPmText; 452 } else { 453 deletedKeyStr = String.format("%d", getValFromKeyCode(deleted)); 454 } 455 Utils.tryAccessibilityAnnounce(mTimePicker, 456 String.format(mDeletedKeyFormat, deletedKeyStr)); 457 updateDisplay(true); 458 } 459 } 460 } else if (keyCode == KeyEvent.KEYCODE_0 || keyCode == KeyEvent.KEYCODE_1 461 || keyCode == KeyEvent.KEYCODE_2 || keyCode == KeyEvent.KEYCODE_3 462 || keyCode == KeyEvent.KEYCODE_4 || keyCode == KeyEvent.KEYCODE_5 463 || keyCode == KeyEvent.KEYCODE_6 || keyCode == KeyEvent.KEYCODE_7 464 || keyCode == KeyEvent.KEYCODE_8 || keyCode == KeyEvent.KEYCODE_9 465 || (!mIs24HourMode && 466 (keyCode == getAmOrPmKeyCode(AM) || keyCode == getAmOrPmKeyCode(PM)))) { 467 if (!mInKbMode) { 468 if (mTimePicker == null) { 469 // Something's wrong, because time picker should definitely not be null. 470 Log.e(TAG, "Unable to initiate keyboard mode, TimePicker was null."); 471 return true; 472 } 473 mTypedTimes.clear(); 474 tryStartingKbMode(keyCode); 475 return true; 476 } 477 // We're already in keyboard mode. 478 if (addKeyIfLegal(keyCode)) { 479 updateDisplay(false); 480 } 481 return true; 482 } 483 return false; 484 } 485 486 /** 487 * Try to start keyboard mode with the specified key, as long as the timepicker is not in the 488 * middle of a touch-event. 489 * @param keyCode The key to use as the first press. Keyboard mode will not be started if the 490 * key is not legal to start with. Or, pass in -1 to get into keyboard mode without a starting 491 * key. 492 */ 493 private void tryStartingKbMode(int keyCode) { 494 if (mTimePicker.trySettingInputEnabled(false) && 495 (keyCode == -1 || addKeyIfLegal(keyCode))) { 496 mInKbMode = true; 497 mDoneButton.setEnabled(false); 498 updateDisplay(false); 499 } 500 } 501 502 private boolean addKeyIfLegal(int keyCode) { 503 // If we're in 24hour mode, we'll need to check if the input is full. If in AM/PM mode, 504 // we'll need to see if AM/PM have been typed. 505 if ((mIs24HourMode && mTypedTimes.size() == 4) || 506 (!mIs24HourMode && isTypedTimeFullyLegal())) { 507 return false; 508 } 509 510 mTypedTimes.add(keyCode); 511 if (!isTypedTimeLegalSoFar()) { 512 deleteLastTypedKey(); 513 return false; 514 } 515 516 int val = getValFromKeyCode(keyCode); 517 Utils.tryAccessibilityAnnounce(mTimePicker, String.format("%d", val)); 518 // Automatically fill in 0's if AM or PM was legally entered. 519 if (isTypedTimeFullyLegal()) { 520 if (!mIs24HourMode && mTypedTimes.size() <= 3) { 521 mTypedTimes.add(mTypedTimes.size() - 1, KeyEvent.KEYCODE_0); 522 mTypedTimes.add(mTypedTimes.size() - 1, KeyEvent.KEYCODE_0); 523 } 524 mDoneButton.setEnabled(true); 525 } 526 527 return true; 528 } 529 530 /** 531 * Traverse the tree to see if the keys that have been typed so far are legal as is, 532 * or may become legal as more keys are typed (excluding backspace). 533 */ 534 private boolean isTypedTimeLegalSoFar() { 535 Node node = mLegalTimesTree; 536 for (int keyCode : mTypedTimes) { 537 node = node.canReach(keyCode); 538 if (node == null) { 539 return false; 540 } 541 } 542 return true; 543 } 544 545 /** 546 * Check if the time that has been typed so far is completely legal, as is. 547 */ 548 private boolean isTypedTimeFullyLegal() { 549 if (mIs24HourMode) { 550 // For 24-hour mode, the time is legal if the hours and minutes are each legal. Note: 551 // getEnteredTime() will ONLY call isTypedTimeFullyLegal() when NOT in 24hour mode. 552 int[] values = getEnteredTime(null); 553 return (values[0] >= 0 && values[1] >= 0 && values[1] < 60); 554 } else { 555 // For AM/PM mode, the time is legal if it contains an AM or PM, as those can only be 556 // legally added at specific times based on the tree's algorithm. 557 return (mTypedTimes.contains(getAmOrPmKeyCode(AM)) || 558 mTypedTimes.contains(getAmOrPmKeyCode(PM))); 559 } 560 } 561 562 private int deleteLastTypedKey() { 563 int deleted = mTypedTimes.remove(mTypedTimes.size() - 1); 564 if (!isTypedTimeFullyLegal()) { 565 mDoneButton.setEnabled(false); 566 } 567 return deleted; 568 } 569 570 /** 571 * Get out of keyboard mode. If there is nothing in typedTimes, revert to TimePicker's time. 572 * @param changeDisplays If true, update the displays with the relevant time. 573 */ 574 private void finishKbMode(boolean updateDisplays) { 575 mInKbMode = false; 576 if (!mTypedTimes.isEmpty()) { 577 int values[] = getEnteredTime(null); 578 mTimePicker.setTime(values[0], values[1]); 579 if (!mIs24HourMode) { 580 mTimePicker.setAmOrPm(values[2]); 581 } 582 mTypedTimes.clear(); 583 } 584 if (updateDisplays) { 585 updateDisplay(false); 586 mTimePicker.trySettingInputEnabled(true); 587 } 588 } 589 590 /** 591 * Update the hours, minutes, and AM/PM displays with the typed times. If the typedTimes is 592 * empty, either show an empty display (filled with the placeholder text), or update from the 593 * timepicker's values. 594 * @param allowEmptyDisplay if true, then if the typedTimes is empty, use the placeholder text. 595 * Otherwise, revert to the timepicker's values. 596 */ 597 private void updateDisplay(boolean allowEmptyDisplay) { 598 if (!allowEmptyDisplay && mTypedTimes.isEmpty()) { 599 int hour = mTimePicker.getHours(); 600 int minute = mTimePicker.getMinutes(); 601 setHour(hour, true); 602 setMinute(minute); 603 if (!mIs24HourMode) { 604 updateAmPmDisplay(hour < 12? AM : PM); 605 } 606 setCurrentItemShowing(mTimePicker.getCurrentItemShowing(), true, true, true); 607 mDoneButton.setEnabled(true); 608 } else { 609 Boolean[] enteredZeros = {false, false}; 610 int[] values = getEnteredTime(enteredZeros); 611 String hourFormat = enteredZeros[0]? "%02d" : "%2d"; 612 String minuteFormat = (enteredZeros[1])? "%02d" : "%2d"; 613 String hourStr = (values[0] == -1)? mDoublePlaceholderText : 614 String.format(hourFormat, values[0]).replace(' ', mPlaceholderText); 615 String minuteStr = (values[1] == -1)? mDoublePlaceholderText : 616 String.format(minuteFormat, values[1]).replace(' ', mPlaceholderText); 617 mHourView.setText(hourStr); 618 mHourSpaceView.setText(hourStr); 619 mHourView.setTextColor(mBlack); 620 mMinuteView.setText(minuteStr); 621 mMinuteSpaceView.setText(minuteStr); 622 mMinuteView.setTextColor(mBlack); 623 if (!mIs24HourMode) { 624 updateAmPmDisplay(values[2]); 625 } 626 } 627 } 628 629 private int getValFromKeyCode(int keyCode) { 630 switch (keyCode) { 631 case KeyEvent.KEYCODE_0: 632 return 0; 633 case KeyEvent.KEYCODE_1: 634 return 1; 635 case KeyEvent.KEYCODE_2: 636 return 2; 637 case KeyEvent.KEYCODE_3: 638 return 3; 639 case KeyEvent.KEYCODE_4: 640 return 4; 641 case KeyEvent.KEYCODE_5: 642 return 5; 643 case KeyEvent.KEYCODE_6: 644 return 6; 645 case KeyEvent.KEYCODE_7: 646 return 7; 647 case KeyEvent.KEYCODE_8: 648 return 8; 649 case KeyEvent.KEYCODE_9: 650 return 9; 651 default: 652 return -1; 653 } 654 } 655 656 /** 657 * Get the currently-entered time, as integer values of the hours and minutes typed. 658 * @param enteredZeros A size-2 boolean array, which the caller should initialize, and which 659 * may then be used for the caller to know whether zeros had been explicitly entered as either 660 * hours of minutes. This is helpful for deciding whether to show the dashes, or actual 0's. 661 * @return A size-3 int array. The first value will be the hours, the second value will be the 662 * minutes, and the third will be either TimePickerDialog.AM or TimePickerDialog.PM. 663 */ 664 private int[] getEnteredTime(Boolean[] enteredZeros) { 665 int amOrPm = -1; 666 int startIndex = 1; 667 if (!mIs24HourMode && isTypedTimeFullyLegal()) { 668 int keyCode = mTypedTimes.get(mTypedTimes.size() - 1); 669 if (keyCode == getAmOrPmKeyCode(AM)) { 670 amOrPm = AM; 671 } else if (keyCode == getAmOrPmKeyCode(PM)){ 672 amOrPm = PM; 673 } 674 startIndex = 2; 675 } 676 int minute = -1; 677 int hour = -1; 678 for (int i = startIndex; i <= mTypedTimes.size(); i++) { 679 int val = getValFromKeyCode(mTypedTimes.get(mTypedTimes.size() - i)); 680 if (i == startIndex) { 681 minute = val; 682 } else if (i == startIndex+1) { 683 minute += 10*val; 684 if (enteredZeros != null && val == 0) { 685 enteredZeros[1] = true; 686 } 687 } else if (i == startIndex+2) { 688 hour = val; 689 } else if (i == startIndex+3) { 690 hour += 10*val; 691 if (enteredZeros != null && val == 0) { 692 enteredZeros[0] = true; 693 } 694 } 695 } 696 697 int[] ret = {hour, minute, amOrPm}; 698 return ret; 699 } 700 701 /** 702 * Get the keycode value for AM and PM in the current language. 703 */ 704 private int getAmOrPmKeyCode(int amOrPm) { 705 // Cache the codes. 706 if (mAmKeyCode == -1 || mPmKeyCode == -1) { 707 // Find the first character in the AM/PM text that is unique. 708 KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD); 709 char amChar; 710 char pmChar; 711 for (int i = 0; i < Math.max(mAmText.length(), mPmText.length()); i++) { 712 amChar = mAmText.toLowerCase(Locale.getDefault()).charAt(i); 713 pmChar = mPmText.toLowerCase(Locale.getDefault()).charAt(i); 714 if (amChar != pmChar) { 715 KeyEvent[] events = kcm.getEvents(new char[]{amChar, pmChar}); 716 // There should be 4 events: a down and up for both AM and PM. 717 if (events != null && events.length == 4) { 718 mAmKeyCode = events[0].getKeyCode(); 719 mPmKeyCode = events[2].getKeyCode(); 720 } else { 721 Log.e(TAG, "Unable to find keycodes for AM and PM."); 722 } 723 break; 724 } 725 } 726 } 727 if (amOrPm == AM) { 728 return mAmKeyCode; 729 } else if (amOrPm == PM) { 730 return mPmKeyCode; 731 } 732 733 return -1; 734 } 735 736 /** 737 * Create a tree for deciding what keys can legally be typed. 738 */ 739 private void generateLegalTimesTree() { 740 // Create a quick cache of numbers to their keycodes. 741 int k0 = KeyEvent.KEYCODE_0; 742 int k1 = KeyEvent.KEYCODE_1; 743 int k2 = KeyEvent.KEYCODE_2; 744 int k3 = KeyEvent.KEYCODE_3; 745 int k4 = KeyEvent.KEYCODE_4; 746 int k5 = KeyEvent.KEYCODE_5; 747 int k6 = KeyEvent.KEYCODE_6; 748 int k7 = KeyEvent.KEYCODE_7; 749 int k8 = KeyEvent.KEYCODE_8; 750 int k9 = KeyEvent.KEYCODE_9; 751 752 // The root of the tree doesn't contain any numbers. 753 mLegalTimesTree = new Node(); 754 if (mIs24HourMode) { 755 // We'll be re-using these nodes, so we'll save them. 756 Node minuteFirstDigit = new Node(k0, k1, k2, k3, k4, k5); 757 Node minuteSecondDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9); 758 // The first digit must be followed by the second digit. 759 minuteFirstDigit.addChild(minuteSecondDigit); 760 761 // The first digit may be 0-1. 762 Node firstDigit = new Node(k0, k1); 763 mLegalTimesTree.addChild(firstDigit); 764 765 // When the first digit is 0-1, the second digit may be 0-5. 766 Node secondDigit = new Node(k0, k1, k2, k3, k4, k5); 767 firstDigit.addChild(secondDigit); 768 // We may now be followed by the first minute digit. E.g. 00:09, 15:58. 769 secondDigit.addChild(minuteFirstDigit); 770 771 // When the first digit is 0-1, and the second digit is 0-5, the third digit may be 6-9. 772 Node thirdDigit = new Node(k6, k7, k8, k9); 773 // The time must now be finished. E.g. 0:55, 1:08. 774 secondDigit.addChild(thirdDigit); 775 776 // When the first digit is 0-1, the second digit may be 6-9. 777 secondDigit = new Node(k6, k7, k8, k9); 778 firstDigit.addChild(secondDigit); 779 // We must now be followed by the first minute digit. E.g. 06:50, 18:20. 780 secondDigit.addChild(minuteFirstDigit); 781 782 // The first digit may be 2. 783 firstDigit = new Node(k2); 784 mLegalTimesTree.addChild(firstDigit); 785 786 // When the first digit is 2, the second digit may be 0-3. 787 secondDigit = new Node(k0, k1, k2, k3); 788 firstDigit.addChild(secondDigit); 789 // We must now be followed by the first minute digit. E.g. 20:50, 23:09. 790 secondDigit.addChild(minuteFirstDigit); 791 792 // When the first digit is 2, the second digit may be 4-5. 793 secondDigit = new Node(k4, k5); 794 firstDigit.addChild(secondDigit); 795 // We must now be followd by the last minute digit. E.g. 2:40, 2:53. 796 secondDigit.addChild(minuteSecondDigit); 797 798 // The first digit may be 3-9. 799 firstDigit = new Node(k3, k4, k5, k6, k7, k8, k9); 800 mLegalTimesTree.addChild(firstDigit); 801 // We must now be followed by the first minute digit. E.g. 3:57, 8:12. 802 firstDigit.addChild(minuteFirstDigit); 803 } else { 804 // We'll need to use the AM/PM node a lot. 805 // Set up AM and PM to respond to "a" and "p". 806 Node ampm = new Node(getAmOrPmKeyCode(AM), getAmOrPmKeyCode(PM)); 807 808 // The first hour digit may be 1. 809 Node firstDigit = new Node(k1); 810 mLegalTimesTree.addChild(firstDigit); 811 // We'll allow quick input of on-the-hour times. E.g. 1pm. 812 firstDigit.addChild(ampm); 813 814 // When the first digit is 1, the second digit may be 0-2. 815 Node secondDigit = new Node(k0, k1, k2); 816 firstDigit.addChild(secondDigit); 817 // Also for quick input of on-the-hour times. E.g. 10pm, 12am. 818 secondDigit.addChild(ampm); 819 820 // When the first digit is 1, and the second digit is 0-2, the third digit may be 0-5. 821 Node thirdDigit = new Node(k0, k1, k2, k3, k4, k5); 822 secondDigit.addChild(thirdDigit); 823 // The time may be finished now. E.g. 1:02pm, 1:25am. 824 thirdDigit.addChild(ampm); 825 826 // When the first digit is 1, the second digit is 0-2, and the third digit is 0-5, 827 // the fourth digit may be 0-9. 828 Node fourthDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9); 829 thirdDigit.addChild(fourthDigit); 830 // The time must be finished now. E.g. 10:49am, 12:40pm. 831 fourthDigit.addChild(ampm); 832 833 // When the first digit is 1, and the second digit is 0-2, the third digit may be 6-9. 834 thirdDigit = new Node(k6, k7, k8, k9); 835 secondDigit.addChild(thirdDigit); 836 // The time must be finished now. E.g. 1:08am, 1:26pm. 837 thirdDigit.addChild(ampm); 838 839 // When the first digit is 1, the second digit may be 3-5. 840 secondDigit = new Node(k3, k4, k5); 841 firstDigit.addChild(secondDigit); 842 843 // When the first digit is 1, and the second digit is 3-5, the third digit may be 0-9. 844 thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9); 845 secondDigit.addChild(thirdDigit); 846 // The time must be finished now. E.g. 1:39am, 1:50pm. 847 thirdDigit.addChild(ampm); 848 849 // The hour digit may be 2-9. 850 firstDigit = new Node(k2, k3, k4, k5, k6, k7, k8, k9); 851 mLegalTimesTree.addChild(firstDigit); 852 // We'll allow quick input of on-the-hour-times. E.g. 2am, 5pm. 853 firstDigit.addChild(ampm); 854 855 // When the first digit is 2-9, the second digit may be 0-5. 856 secondDigit = new Node(k0, k1, k2, k3, k4, k5); 857 firstDigit.addChild(secondDigit); 858 859 // When the first digit is 2-9, and the second digit is 0-5, the third digit may be 0-9. 860 thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9); 861 secondDigit.addChild(thirdDigit); 862 // The time must be finished now. E.g. 2:57am, 9:30pm. 863 thirdDigit.addChild(ampm); 864 } 865 } 866 867 /** 868 * Simple node class to be used for traversal to check for legal times. 869 * mLegalKeys represents the keys that can be typed to get to the node. 870 * mChildren are the children that can be reached from this node. 871 */ 872 private class Node { 873 private int[] mLegalKeys; 874 private ArrayList<Node> mChildren; 875 876 public Node(int... legalKeys) { 877 mLegalKeys = legalKeys; 878 mChildren = new ArrayList<Node>(); 879 } 880 881 public void addChild(Node child) { 882 mChildren.add(child); 883 } 884 885 public boolean containsKey(int key) { 886 for (int i = 0; i < mLegalKeys.length; i++) { 887 if (mLegalKeys[i] == key) { 888 return true; 889 } 890 } 891 return false; 892 } 893 894 public Node canReach(int key) { 895 if (mChildren == null) { 896 return null; 897 } 898 for (Node child : mChildren) { 899 if (child.containsKey(key)) { 900 return child; 901 } 902 } 903 return null; 904 } 905 } 906 907 private class KeyboardListener implements OnKeyListener { 908 @Override 909 public boolean onKey(View v, int keyCode, KeyEvent event) { 910 if (event.getAction() == KeyEvent.ACTION_UP) { 911 return processKeyUp(keyCode); 912 } 913 return false; 914 } 915 } 916} 917