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