Debian Codegraph @

core/java/android/widget/DatePickerCalendarDelegate.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2014 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
17 package android.widget;
18
19 import android.annotation.Nullable;
20 import android.content.Context;
21 import android.content.res.ColorStateList;
22 import android.content.res.Configuration;
23 import android.content.res.Resources;
24 import android.content.res.TypedArray;
25 import android.icu.text.DateFormat;
26 import android.icu.text.DisplayContext;
27 import android.icu.util.Calendar;
28 import android.os.Parcelable;
29 import android.util.AttributeSet;
30 import android.util.StateSet;
31 import android.view.HapticFeedbackConstants;
32 import android.view.LayoutInflater;
33 import android.view.View;
34 import android.view.View.OnClickListener;
35 import android.view.ViewGroup;
36 import android.view.accessibility.AccessibilityEvent;
37 import android.widget.DayPickerView.OnDaySelectedListener;
38 import android.widget.YearPickerView.OnYearSelectedListener;
39
40 import com.android.internal.R;
41
42 import java.util.Locale;
43
44 /**
45 * A delegate for picking up a date (day / month / year).
46 */
47 class DatePickerCalendarDelegate extends DatePicker.AbstractDatePickerDelegate {
48 private static final int USE_LOCALE = 0;
49
50 private static final int UNINITIALIZED = -1;
51 private static final int VIEW_MONTH_DAY = 0;
52 private static final int VIEW_YEAR = 1;
53
54 private static final int DEFAULT_START_YEAR = 1900;
55 private static final int DEFAULT_END_YEAR = 2100;
56
57 private static final int ANIMATION_DURATION = 300;
58
59 private static final int[] ATTRS_TEXT_COLOR = new int[] {
60 com.android.internal.R.attr.textColor};
61 private static final int[] ATTRS_DISABLED_ALPHA = new int[] {
62 com.android.internal.R.attr.disabledAlpha};
63
64 private DateFormat mYearFormat;
65 private DateFormat mMonthDayFormat;
66
67 // Top-level container.
68 private ViewGroup mContainer;
69
70 // Header views.
71 private TextView mHeaderYear;
72 private TextView mHeaderMonthDay;
73
74 // Picker views.
75 private ViewAnimator mAnimator;
76 private DayPickerView mDayPickerView;
77 private YearPickerView mYearPickerView;
78
79 // Accessibility strings.
80 private String mSelectDay;
81 private String mSelectYear;
82
83 private int mCurrentView = UNINITIALIZED;
84
85 private final Calendar mTempDate;
86 private final Calendar mMinDate;
87 private final Calendar mMaxDate;
88
89 private int mFirstDayOfWeek = USE_LOCALE;
90
91 public DatePickerCalendarDelegate(DatePicker delegator, Context context, AttributeSet attrs,
92 int defStyleAttr, int defStyleRes) {
93 super(delegator, context);
94
95 final Locale locale = mCurrentLocale;
96 mCurrentDate = Calendar.getInstance(locale);
97 mTempDate = Calendar.getInstance(locale);
98 mMinDate = Calendar.getInstance(locale);
99 mMaxDate = Calendar.getInstance(locale);
100
101 mMinDate.set(DEFAULT_START_YEAR, Calendar.JANUARY, 1);
102 mMaxDate.set(DEFAULT_END_YEAR, Calendar.DECEMBER, 31);
103
104 final Resources res = mDelegator.getResources();
105 final TypedArray a = mContext.obtainStyledAttributes(attrs,
106 R.styleable.DatePicker, defStyleAttr, defStyleRes);
107 final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(
108 Context.LAYOUT_INFLATER_SERVICE);
109 final int layoutResourceId = a.getResourceId(
110 R.styleable.DatePicker_internalLayout, R.layout.date_picker_material);
111
112 // Set up and attach container.
113 mContainer = (ViewGroup) inflater.inflate(layoutResourceId, mDelegator, false);
114 mContainer.setSaveFromParentEnabled(false);
115 mDelegator.addView(mContainer);
116
117 // Set up header views.
118 final ViewGroup header = mContainer.findViewById(R.id.date_picker_header);
119 mHeaderYear = header.findViewById(R.id.date_picker_header_year);
120 mHeaderYear.setOnClickListener(mOnHeaderClickListener);
121 mHeaderMonthDay = header.findViewById(R.id.date_picker_header_date);
122 mHeaderMonthDay.setOnClickListener(mOnHeaderClickListener);
123
124 // For the sake of backwards compatibility, attempt to extract the text
125 // color from the header month text appearance. If it's set, we'll let
126 // that override the "real" header text color.
127 ColorStateList headerTextColor = null;
128
129 @SuppressWarnings("deprecation")
130 final int monthHeaderTextAppearance = a.getResourceId(
131 R.styleable.DatePicker_headerMonthTextAppearance, 0);
132 if (monthHeaderTextAppearance != 0) {
133 final TypedArray textAppearance = mContext.obtainStyledAttributes(null,
134 ATTRS_TEXT_COLOR, 0, monthHeaderTextAppearance);
135 final ColorStateList legacyHeaderTextColor = textAppearance.getColorStateList(0);
136 headerTextColor = applyLegacyColorFixes(legacyHeaderTextColor);
137 textAppearance.recycle();
138 }
139
140 if (headerTextColor == null) {
141 headerTextColor = a.getColorStateList(R.styleable.DatePicker_headerTextColor);
142 }
143
144 if (headerTextColor != null) {
145 mHeaderYear.setTextColor(headerTextColor);
146 mHeaderMonthDay.setTextColor(headerTextColor);
147 }
148
149 // Set up header background, if available.
150 if (a.hasValueOrEmpty(R.styleable.DatePicker_headerBackground)) {
151 header.setBackground(a.getDrawable(R.styleable.DatePicker_headerBackground));
152 }
153
154 a.recycle();
155
156 // Set up picker container.
157 mAnimator = mContainer.findViewById(R.id.animator);
158
159 // Set up day picker view.
160 mDayPickerView = mAnimator.findViewById(R.id.date_picker_day_picker);
161 mDayPickerView.setFirstDayOfWeek(mFirstDayOfWeek);
162 mDayPickerView.setMinDate(mMinDate.getTimeInMillis());
163 mDayPickerView.setMaxDate(mMaxDate.getTimeInMillis());
164 mDayPickerView.setDate(mCurrentDate.getTimeInMillis());
165 mDayPickerView.setOnDaySelectedListener(mOnDaySelectedListener);
166
167 // Set up year picker view.
168 mYearPickerView = mAnimator.findViewById(R.id.date_picker_year_picker);
169 mYearPickerView.setRange(mMinDate, mMaxDate);
170 mYearPickerView.setYear(mCurrentDate.get(Calendar.YEAR));
171 mYearPickerView.setOnYearSelectedListener(mOnYearSelectedListener);
172
173 // Set up content descriptions.
174 mSelectDay = res.getString(R.string.select_day);
175 mSelectYear = res.getString(R.string.select_year);
176
177 // Initialize for current locale. This also initializes the date, so no
178 // need to call onDateChanged.
179 onLocaleChanged(mCurrentLocale);
180
181 setCurrentView(VIEW_MONTH_DAY);
182 }
183
184 /**
185 * The legacy text color might have been poorly defined. Ensures that it
186 * has an appropriate activated state, using the selected state if one
187 * exists or modifying the default text color otherwise.
188 *
189 * @param color a legacy text color, or {@code null}
190 * @return a color state list with an appropriate activated state, or
191 * {@code null} if a valid activated state could not be generated
192 */
193 @Nullable
194 private ColorStateList applyLegacyColorFixes(@Nullable ColorStateList color) {
195 if (color == null || color.hasState(R.attr.state_activated)) {
196 return color;
197 }
198
199 final int activatedColor;
200 final int defaultColor;
201 if (color.hasState(R.attr.state_selected)) {
202 activatedColor = color.getColorForState(StateSet.get(
203 StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_SELECTED), 0);
204 defaultColor = color.getColorForState(StateSet.get(
205 StateSet.VIEW_STATE_ENABLED), 0);
206 } else {
207 activatedColor = color.getDefaultColor();
208
209 // Generate a non-activated color using the disabled alpha.
210 final TypedArray ta = mContext.obtainStyledAttributes(ATTRS_DISABLED_ALPHA);
211 final float disabledAlpha = ta.getFloat(0, 0.30f);
212 ta.recycle();
213 defaultColor = multiplyAlphaComponent(activatedColor, disabledAlpha);
214 }
215
216 if (activatedColor == 0 || defaultColor == 0) {
217 // We somehow failed to obtain the colors.
218 return null;
219 }
220
221 final int[][] stateSet = new int[][] {{ R.attr.state_activated }, {}};
222 final int[] colors = new int[] { activatedColor, defaultColor };
223 return new ColorStateList(stateSet, colors);
224 }
225
226 private int multiplyAlphaComponent(int color, float alphaMod) {
227 final int srcRgb = color & 0xFFFFFF;
228 final int srcAlpha = (color >> 24) & 0xFF;
229 final int dstAlpha = (int) (srcAlpha * alphaMod + 0.5f);
230 return srcRgb | (dstAlpha << 24);
231 }
232
233 /**
234 * Listener called when the user selects a day in the day picker view.
235 */
236 private final OnDaySelectedListener mOnDaySelectedListener = new OnDaySelectedListener() {
237 @Override
238 public void onDaySelected(DayPickerView view, Calendar day) {
239 mCurrentDate.setTimeInMillis(day.getTimeInMillis());
240 onDateChanged(true, true);
241 }
242 };
243
244 /**
245 * Listener called when the user selects a year in the year picker view.
246 */
247 private final OnYearSelectedListener mOnYearSelectedListener = new OnYearSelectedListener() {
248 @Override
249 public void onYearChanged(YearPickerView view, int year) {
250 // If the newly selected month / year does not contain the
251 // currently selected day number, change the selected day number
252 // to the last day of the selected month or year.
253 // e.g. Switching from Mar to Apr when Mar 31 is selected -> Apr 30
254 // e.g. Switching from 2012 to 2013 when Feb 29, 2012 is selected -> Feb 28, 2013
255 final int day = mCurrentDate.get(Calendar.DAY_OF_MONTH);
256 final int month = mCurrentDate.get(Calendar.MONTH);
257 final int daysInMonth = getDaysInMonth(month, year);
258 if (day > daysInMonth) {
259 mCurrentDate.set(Calendar.DAY_OF_MONTH, daysInMonth);
260 }
261
262 mCurrentDate.set(Calendar.YEAR, year);
263 if (mCurrentDate.compareTo(mMinDate) < 0) {
264 mCurrentDate.setTimeInMillis(mMinDate.getTimeInMillis());
265 } else if (mCurrentDate.compareTo(mMaxDate) > 0) {
266 mCurrentDate.setTimeInMillis(mMaxDate.getTimeInMillis());
267 }
268 onDateChanged(true, true);
269
270 // Automatically switch to day picker.
271 setCurrentView(VIEW_MONTH_DAY);
272
273 // Switch focus back to the year text.
274 mHeaderYear.requestFocus();
275 }
276 };
277
278 /**
279 * Listener called when the user clicks on a header item.
280 */
281 private final OnClickListener mOnHeaderClickListener = v -> {
282 tryVibrate();
283
284 switch (v.getId()) {
285 case R.id.date_picker_header_year:
286 setCurrentView(VIEW_YEAR);
287 break;
288 case R.id.date_picker_header_date:
289 setCurrentView(VIEW_MONTH_DAY);
290 break;
291 }
292 };
293
294 @Override
295 protected void onLocaleChanged(Locale locale) {
296 final TextView headerYear = mHeaderYear;
297 if (headerYear == null) {
298 // Abort, we haven't initialized yet. This method will get called
299 // again later after everything has been set up.
300 return;
301 }
302
303 // Update the date formatter.
304 mMonthDayFormat = DateFormat.getInstanceForSkeleton("EMMMd", locale);
305 mMonthDayFormat.setContext(DisplayContext.CAPITALIZATION_FOR_STANDALONE);
306 mYearFormat = DateFormat.getInstanceForSkeleton("y", locale);
307
308 // Update the header text.
309 onCurrentDateChanged(false);
310 }
311
312 private void onCurrentDateChanged(boolean announce) {
313 if (mHeaderYear == null) {
314 // Abort, we haven't initialized yet. This method will get called
315 // again later after everything has been set up.
316 return;
317 }
318
319 final String year = mYearFormat.format(mCurrentDate.getTime());
320 mHeaderYear.setText(year);
321
322 final String monthDay = mMonthDayFormat.format(mCurrentDate.getTime());
323 mHeaderMonthDay.setText(monthDay);
324
325 // TODO: This should use live regions.
326 if (announce) {
327 mAnimator.announceForAccessibility(getFormattedCurrentDate());
328 }
329 }
330
331 private void setCurrentView(final int viewIndex) {
332 switch (viewIndex) {
333 case VIEW_MONTH_DAY:
334 mDayPickerView.setDate(mCurrentDate.getTimeInMillis());
335
336 if (mCurrentView != viewIndex) {
337 mHeaderMonthDay.setActivated(true);
338 mHeaderYear.setActivated(false);
339 mAnimator.setDisplayedChild(VIEW_MONTH_DAY);
340 mCurrentView = viewIndex;
341 }
342
343 mAnimator.announceForAccessibility(mSelectDay);
344 break;
345 case VIEW_YEAR:
346 final int year = mCurrentDate.get(Calendar.YEAR);
347 mYearPickerView.setYear(year);
348 mYearPickerView.post(() -> {
349 mYearPickerView.requestFocus();
350 final View selected = mYearPickerView.getSelectedView();
351 if (selected != null) {
352 selected.requestFocus();
353 }
354 });
355
356 if (mCurrentView != viewIndex) {
357 mHeaderMonthDay.setActivated(false);
358 mHeaderYear.setActivated(true);
359 mAnimator.setDisplayedChild(VIEW_YEAR);
360 mCurrentView = viewIndex;
361 }
362
363 mAnimator.announceForAccessibility(mSelectYear);
364 break;
365 }
366 }
367
368 @Override
369 public void init(int year, int month, int dayOfMonth,
370 DatePicker.OnDateChangedListener callBack) {
371 setDate(year, month, dayOfMonth);
372 onDateChanged(false, false);
373
374 mOnDateChangedListener = callBack;
375 }
376
377 @Override
378 public void updateDate(int year, int month, int dayOfMonth) {
379 setDate(year, month, dayOfMonth);
380 onDateChanged(false, true);
381 }
382
383 private void setDate(int year, int month, int dayOfMonth) {
384 mCurrentDate.set(Calendar.YEAR, year);
385 mCurrentDate.set(Calendar.MONTH, month);
386 mCurrentDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
387 resetAutofilledValue();
388 }
389
390 private void onDateChanged(boolean fromUser, boolean callbackToClient) {
391 final int year = mCurrentDate.get(Calendar.YEAR);
392
393 if (callbackToClient
394 && (mOnDateChangedListener != null || mAutoFillChangeListener != null)) {
395 final int monthOfYear = mCurrentDate.get(Calendar.MONTH);
396 final int dayOfMonth = mCurrentDate.get(Calendar.DAY_OF_MONTH);
397 if (mOnDateChangedListener != null) {
398 mOnDateChangedListener.onDateChanged(mDelegator, year, monthOfYear, dayOfMonth);
399 }
400 if (mAutoFillChangeListener != null) {
401 mAutoFillChangeListener.onDateChanged(mDelegator, year, monthOfYear, dayOfMonth);
402 }
403 }
404
405 mDayPickerView.setDate(mCurrentDate.getTimeInMillis());
406 mYearPickerView.setYear(year);
407
408 onCurrentDateChanged(fromUser);
409
410 if (fromUser) {
411 tryVibrate();
412 }
413 }
414
415 @Override
416 public int getYear() {
417 return mCurrentDate.get(Calendar.YEAR);
418 }
419
420 @Override
421 public int getMonth() {
422 return mCurrentDate.get(Calendar.MONTH);
423 }
424
425 @Override
426 public int getDayOfMonth() {
427 return mCurrentDate.get(Calendar.DAY_OF_MONTH);
428 }
429
430 @Override
431 public void setMinDate(long minDate) {
432 mTempDate.setTimeInMillis(minDate);
433 if (mTempDate.get(Calendar.YEAR) == mMinDate.get(Calendar.YEAR)
434 && mTempDate.get(Calendar.DAY_OF_YEAR) == mMinDate.get(Calendar.DAY_OF_YEAR)) {
435 // Same day, no-op.
436 return;
437 }
438 if (mCurrentDate.before(mTempDate)) {
439 mCurrentDate.setTimeInMillis(minDate);
440 onDateChanged(false, true);
441 }
442 mMinDate.setTimeInMillis(minDate);
443 mDayPickerView.setMinDate(minDate);
444 mYearPickerView.setRange(mMinDate, mMaxDate);
445 }
446
447 @Override
448 public Calendar getMinDate() {
449 return mMinDate;
450 }
451
452 @Override
453 public void setMaxDate(long maxDate) {
454 mTempDate.setTimeInMillis(maxDate);
455 if (mTempDate.get(Calendar.YEAR) == mMaxDate.get(Calendar.YEAR)
456 && mTempDate.get(Calendar.DAY_OF_YEAR) == mMaxDate.get(Calendar.DAY_OF_YEAR)) {
457 // Same day, no-op.
458 return;
459 }
460 if (mCurrentDate.after(mTempDate)) {
461 mCurrentDate.setTimeInMillis(maxDate);
462 onDateChanged(false, true);
463 }
464 mMaxDate.setTimeInMillis(maxDate);
465 mDayPickerView.setMaxDate(maxDate);
466 mYearPickerView.setRange(mMinDate, mMaxDate);
467 }
468
469 @Override
470 public Calendar getMaxDate() {
471 return mMaxDate;
472 }
473
474 @Override
475 public void setFirstDayOfWeek(int firstDayOfWeek) {
476 mFirstDayOfWeek = firstDayOfWeek;
477
478 mDayPickerView.setFirstDayOfWeek(firstDayOfWeek);
479 }
480
481 @Override
482 public int getFirstDayOfWeek() {
483 if (mFirstDayOfWeek != USE_LOCALE) {
484 return mFirstDayOfWeek;
485 }
486 return mCurrentDate.getFirstDayOfWeek();
487 }
488
489 @Override
490 public void setEnabled(boolean enabled) {
491 mContainer.setEnabled(enabled);
492 mDayPickerView.setEnabled(enabled);
493 mYearPickerView.setEnabled(enabled);
494 mHeaderYear.setEnabled(enabled);
495 mHeaderMonthDay.setEnabled(enabled);
496 }
497
498 @Override
499 public boolean isEnabled() {
500 return mContainer.isEnabled();
501 }
502
503 @Override
504 public CalendarView getCalendarView() {
505 throw new UnsupportedOperationException("Not supported by calendar-mode DatePicker");
506 }
507
508 @Override
509 public void setCalendarViewShown(boolean shown) {
510 // No-op for compatibility with the old DatePicker.
511 }
512
513 @Override
514 public boolean getCalendarViewShown() {
515 return false;
516 }
517
518 @Override
519 public void setSpinnersShown(boolean shown) {
520 // No-op for compatibility with the old DatePicker.
521 }
522
523 @Override
524 public boolean getSpinnersShown() {
525 return false;
526 }
527
528 @Override
529 public void onConfigurationChanged(Configuration newConfig) {
530 setCurrentLocale(newConfig.locale);
531 }
532
533 @Override
534 public Parcelable onSaveInstanceState(Parcelable superState) {
535 final int year = mCurrentDate.get(Calendar.YEAR);
536 final int month = mCurrentDate.get(Calendar.MONTH);
537 final int day = mCurrentDate.get(Calendar.DAY_OF_MONTH);
538
539 int listPosition = -1;
540 int listPositionOffset = -1;
541
542 if (mCurrentView == VIEW_MONTH_DAY) {
543 listPosition = mDayPickerView.getMostVisiblePosition();
544 } else if (mCurrentView == VIEW_YEAR) {
545 listPosition = mYearPickerView.getFirstVisiblePosition();
546 listPositionOffset = mYearPickerView.getFirstPositionOffset();
547 }
548
549 return new SavedState(superState, year, month, day, mMinDate.getTimeInMillis(),
550 mMaxDate.getTimeInMillis(), mCurrentView, listPosition, listPositionOffset);
551 }
552
553 @Override
554 public void onRestoreInstanceState(Parcelable state) {
555 if (state instanceof SavedState) {
556 final SavedState ss = (SavedState) state;
557
558 // TODO: Move instance state into DayPickerView, YearPickerView.
559 mCurrentDate.set(ss.getSelectedYear(), ss.getSelectedMonth(), ss.getSelectedDay());
560 mMinDate.setTimeInMillis(ss.getMinDate());
561 mMaxDate.setTimeInMillis(ss.getMaxDate());
562
563 onCurrentDateChanged(false);
564
565 final int currentView = ss.getCurrentView();
566 setCurrentView(currentView);
567
568 final int listPosition = ss.getListPosition();
569 if (listPosition != -1) {
570 if (currentView == VIEW_MONTH_DAY) {
571 mDayPickerView.setPosition(listPosition);
572 } else if (currentView == VIEW_YEAR) {
573 final int listPositionOffset = ss.getListPositionOffset();
574 mYearPickerView.setSelectionFromTop(listPosition, listPositionOffset);
575 }
576 }
577 }
578 }
579
580 @Override
581 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
582 onPopulateAccessibilityEvent(event);
583 return true;
584 }
585
586 public CharSequence getAccessibilityClassName() {
587 return DatePicker.class.getName();
588 }
589
590 private static int getDaysInMonth(int month, int year) {
591 switch (month) {
592 case Calendar.JANUARY:
593 case Calendar.MARCH:
594 case Calendar.MAY:
595 case Calendar.JULY:
596 case Calendar.AUGUST:
597 case Calendar.OCTOBER:
598 case Calendar.DECEMBER:
599 return 31;
600 case Calendar.APRIL:
601 case Calendar.JUNE:
602 case Calendar.SEPTEMBER:
603 case Calendar.NOVEMBER:
604 return 30;
605 case Calendar.FEBRUARY:
606 return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 29 : 28;
607 default:
608 throw new IllegalArgumentException("Invalid Month");
609 }
610 }
611
612 private void tryVibrate() {
613 mDelegator.performHapticFeedback(HapticFeedbackConstants.CALENDAR_DATE);
614 }
615 }