DayPickerView.java revision b12172ef473450da7d1ad6b3fcae4ac41bec2395
1/* 2 * Copyright (C) 2015 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 android.widget; 18 19import com.android.internal.R; 20import com.android.internal.widget.ViewPager; 21import com.android.internal.widget.ViewPager.OnPageChangeListener; 22 23import android.annotation.Nullable; 24import android.content.Context; 25import android.content.res.ColorStateList; 26import android.content.res.TypedArray; 27import android.util.AttributeSet; 28import android.util.MathUtils; 29import android.view.LayoutInflater; 30import android.view.View; 31import android.view.ViewGroup; 32import android.view.accessibility.AccessibilityManager; 33 34import java.util.Calendar; 35import java.util.Locale; 36 37import libcore.icu.LocaleData; 38 39class DayPickerView extends ViewGroup { 40 private static final int DEFAULT_LAYOUT = R.layout.day_picker_content_material; 41 private static final int DEFAULT_START_YEAR = 1900; 42 private static final int DEFAULT_END_YEAR = 2100; 43 44 private static final int[] ATTRS_TEXT_COLOR = new int[] { R.attr.textColor }; 45 46 private final Calendar mSelectedDay = Calendar.getInstance(); 47 private final Calendar mMinDate = Calendar.getInstance(); 48 private final Calendar mMaxDate = Calendar.getInstance(); 49 50 private final AccessibilityManager mAccessibilityManager; 51 52 private final ViewPager mViewPager; 53 private final ImageButton mPrevButton; 54 private final ImageButton mNextButton; 55 56 private final DayPickerPagerAdapter mAdapter; 57 58 /** Temporary calendar used for date calculations. */ 59 private Calendar mTempCalendar; 60 61 private OnDaySelectedListener mOnDaySelectedListener; 62 63 public DayPickerView(Context context) { 64 this(context, null); 65 } 66 67 public DayPickerView(Context context, @Nullable AttributeSet attrs) { 68 this(context, attrs, R.attr.calendarViewStyle); 69 } 70 71 public DayPickerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 72 this(context, attrs, defStyleAttr, 0); 73 } 74 75 public DayPickerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, 76 int defStyleRes) { 77 super(context, attrs, defStyleAttr, defStyleRes); 78 79 mAccessibilityManager = (AccessibilityManager) context.getSystemService( 80 Context.ACCESSIBILITY_SERVICE); 81 82 final TypedArray a = context.obtainStyledAttributes(attrs, 83 R.styleable.CalendarView, defStyleAttr, defStyleRes); 84 85 final int firstDayOfWeek = a.getInt(R.styleable.CalendarView_firstDayOfWeek, 86 LocaleData.get(Locale.getDefault()).firstDayOfWeek); 87 88 final String minDate = a.getString(R.styleable.CalendarView_minDate); 89 final String maxDate = a.getString(R.styleable.CalendarView_maxDate); 90 91 final int monthTextAppearanceResId = a.getResourceId( 92 R.styleable.CalendarView_monthTextAppearance, 93 R.style.TextAppearance_Material_Widget_Calendar_Month); 94 final int dayOfWeekTextAppearanceResId = a.getResourceId( 95 R.styleable.CalendarView_weekDayTextAppearance, 96 R.style.TextAppearance_Material_Widget_Calendar_DayOfWeek); 97 final int dayTextAppearanceResId = a.getResourceId( 98 R.styleable.CalendarView_dateTextAppearance, 99 R.style.TextAppearance_Material_Widget_Calendar_Day); 100 101 final ColorStateList daySelectorColor = a.getColorStateList( 102 R.styleable.CalendarView_daySelectorColor); 103 104 a.recycle(); 105 106 // Set up adapter. 107 mAdapter = new DayPickerPagerAdapter(context, 108 R.layout.date_picker_month_item_material, R.id.month_view); 109 mAdapter.setMonthTextAppearance(monthTextAppearanceResId); 110 mAdapter.setDayOfWeekTextAppearance(dayOfWeekTextAppearanceResId); 111 mAdapter.setDayTextAppearance(dayTextAppearanceResId); 112 mAdapter.setDaySelectorColor(daySelectorColor); 113 114 final LayoutInflater inflater = LayoutInflater.from(context); 115 final ViewGroup content = (ViewGroup) inflater.inflate(DEFAULT_LAYOUT, this, false); 116 117 // Transfer all children from content to here. 118 while (content.getChildCount() > 0) { 119 final View child = content.getChildAt(0); 120 content.removeViewAt(0); 121 addView(child); 122 } 123 124 mPrevButton = (ImageButton) findViewById(R.id.prev); 125 mPrevButton.setOnClickListener(mOnClickListener); 126 127 mNextButton = (ImageButton) findViewById(R.id.next); 128 mNextButton.setOnClickListener(mOnClickListener); 129 130 mViewPager = (ViewPager) findViewById(R.id.day_picker_view_pager); 131 mViewPager.setAdapter(mAdapter); 132 mViewPager.setOnPageChangeListener(mOnPageChangedListener); 133 134 // Proxy the month text color into the previous and next buttons. 135 if (monthTextAppearanceResId != 0) { 136 final TypedArray ta = mContext.obtainStyledAttributes(null, 137 ATTRS_TEXT_COLOR, 0, monthTextAppearanceResId); 138 final ColorStateList monthColor = ta.getColorStateList(0); 139 if (monthColor != null) { 140 mPrevButton.setImageTintList(monthColor); 141 mNextButton.setImageTintList(monthColor); 142 } 143 ta.recycle(); 144 } 145 146 // Set up min and max dates. 147 final Calendar tempDate = Calendar.getInstance(); 148 if (!CalendarView.parseDate(minDate, tempDate)) { 149 tempDate.set(DEFAULT_START_YEAR, Calendar.JANUARY, 1); 150 } 151 final long minDateMillis = tempDate.getTimeInMillis(); 152 153 if (!CalendarView.parseDate(maxDate, tempDate)) { 154 tempDate.set(DEFAULT_END_YEAR, Calendar.DECEMBER, 31); 155 } 156 final long maxDateMillis = tempDate.getTimeInMillis(); 157 158 if (maxDateMillis < minDateMillis) { 159 throw new IllegalArgumentException("maxDate must be >= minDate"); 160 } 161 162 final long setDateMillis = MathUtils.constrain( 163 System.currentTimeMillis(), minDateMillis, maxDateMillis); 164 165 setFirstDayOfWeek(firstDayOfWeek); 166 setMinDate(minDateMillis); 167 setMaxDate(maxDateMillis); 168 setDate(setDateMillis, false); 169 170 // Proxy selection callbacks to our own listener. 171 mAdapter.setOnDaySelectedListener(new DayPickerPagerAdapter.OnDaySelectedListener() { 172 @Override 173 public void onDaySelected(DayPickerPagerAdapter adapter, Calendar day) { 174 if (mOnDaySelectedListener != null) { 175 mOnDaySelectedListener.onDaySelected(DayPickerView.this, day); 176 } 177 } 178 }); 179 180 updateButtonVisibility(mViewPager.getCurrentItem()); 181 } 182 183 private void updateButtonVisibility(int position) { 184 final boolean hasPrev = position > 0; 185 final boolean hasNext = position < (mAdapter.getCount() - 1); 186 mPrevButton.setVisibility(hasPrev ? View.VISIBLE : View.INVISIBLE); 187 mNextButton.setVisibility(hasNext ? View.VISIBLE : View.INVISIBLE); 188 } 189 190 @Override 191 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 192 final ViewPager viewPager = mViewPager; 193 measureChild(viewPager, widthMeasureSpec, heightMeasureSpec); 194 195 final int measuredWidthAndState = viewPager.getMeasuredWidthAndState(); 196 final int measuredHeightAndState = viewPager.getMeasuredHeightAndState(); 197 setMeasuredDimension(measuredWidthAndState, measuredHeightAndState); 198 199 final int pagerWidth = viewPager.getMeasuredWidth(); 200 final int pagerHeight = viewPager.getMeasuredHeight(); 201 final int buttonWidthSpec = MeasureSpec.makeMeasureSpec(pagerWidth, MeasureSpec.AT_MOST); 202 final int buttonHeightSpec = MeasureSpec.makeMeasureSpec(pagerHeight, MeasureSpec.AT_MOST); 203 mPrevButton.measure(buttonWidthSpec, buttonHeightSpec); 204 mNextButton.measure(buttonWidthSpec, buttonHeightSpec); 205 } 206 207 @Override 208 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 209 super.onRtlPropertiesChanged(layoutDirection); 210 211 requestLayout(); 212 } 213 214 @Override 215 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 216 final ImageButton leftButton; 217 final ImageButton rightButton; 218 if (isLayoutRtl()) { 219 leftButton = mNextButton; 220 rightButton = mPrevButton; 221 } else { 222 leftButton = mPrevButton; 223 rightButton = mNextButton; 224 } 225 226 final int width = right - left; 227 final int height = bottom - top; 228 mViewPager.layout(0, 0, width, height); 229 230 final SimpleMonthView monthView = (SimpleMonthView) mViewPager.getChildAt(0); 231 final int monthHeight = monthView.getMonthHeight(); 232 final int cellWidth = monthView.getCellWidth(); 233 234 // Vertically center the previous/next buttons within the month 235 // header, horizontally center within the day cell. 236 final int leftDW = leftButton.getMeasuredWidth(); 237 final int leftDH = leftButton.getMeasuredHeight(); 238 final int leftIconTop = monthView.getPaddingTop() + (monthHeight - leftDH) / 2; 239 final int leftIconLeft = monthView.getPaddingLeft() + (cellWidth - leftDW) / 2; 240 leftButton.layout(leftIconLeft, leftIconTop, leftIconLeft + leftDW, leftIconTop + leftDH); 241 242 final int rightDW = rightButton.getMeasuredWidth(); 243 final int rightDH = rightButton.getMeasuredHeight(); 244 final int rightIconTop = monthView.getPaddingTop() + (monthHeight - rightDH) / 2; 245 final int rightIconRight = width - monthView.getPaddingRight() - (cellWidth - rightDW) / 2; 246 rightButton.layout(rightIconRight - rightDW, rightIconTop, 247 rightIconRight, rightIconTop + rightDH); 248 } 249 250 public void setDayOfWeekTextAppearance(int resId) { 251 mAdapter.setDayOfWeekTextAppearance(resId); 252 } 253 254 public int getDayOfWeekTextAppearance() { 255 return mAdapter.getDayOfWeekTextAppearance(); 256 } 257 258 public void setDayTextAppearance(int resId) { 259 mAdapter.setDayTextAppearance(resId); 260 } 261 262 public int getDayTextAppearance() { 263 return mAdapter.getDayTextAppearance(); 264 } 265 266 /** 267 * Sets the currently selected date to the specified timestamp. Jumps 268 * immediately to the new date. To animate to the new date, use 269 * {@link #setDate(long, boolean)}. 270 * 271 * @param timeInMillis the target day in milliseconds 272 */ 273 public void setDate(long timeInMillis) { 274 setDate(timeInMillis, false); 275 } 276 277 /** 278 * Sets the currently selected date to the specified timestamp. Jumps 279 * immediately to the new date, optionally animating the transition. 280 * 281 * @param timeInMillis the target day in milliseconds 282 * @param animate whether to smooth scroll to the new position 283 */ 284 public void setDate(long timeInMillis, boolean animate) { 285 setDate(timeInMillis, animate, true); 286 } 287 288 /** 289 * Moves to the month containing the specified day, optionally setting the 290 * day as selected. 291 * 292 * @param timeInMillis the target day in milliseconds 293 * @param animate whether to smooth scroll to the new position 294 * @param setSelected whether to set the specified day as selected 295 */ 296 private void setDate(long timeInMillis, boolean animate, boolean setSelected) { 297 if (setSelected) { 298 mSelectedDay.setTimeInMillis(timeInMillis); 299 } 300 301 final int position = getPositionFromDay(timeInMillis); 302 if (position != mViewPager.getCurrentItem()) { 303 mViewPager.setCurrentItem(position, animate); 304 } 305 306 mTempCalendar.setTimeInMillis(timeInMillis); 307 mAdapter.setSelectedDay(mTempCalendar); 308 } 309 310 public long getDate() { 311 return mSelectedDay.getTimeInMillis(); 312 } 313 314 public void setFirstDayOfWeek(int firstDayOfWeek) { 315 mAdapter.setFirstDayOfWeek(firstDayOfWeek); 316 } 317 318 public int getFirstDayOfWeek() { 319 return mAdapter.getFirstDayOfWeek(); 320 } 321 322 public void setMinDate(long timeInMillis) { 323 mMinDate.setTimeInMillis(timeInMillis); 324 onRangeChanged(); 325 } 326 327 public long getMinDate() { 328 return mMinDate.getTimeInMillis(); 329 } 330 331 public void setMaxDate(long timeInMillis) { 332 mMaxDate.setTimeInMillis(timeInMillis); 333 onRangeChanged(); 334 } 335 336 public long getMaxDate() { 337 return mMaxDate.getTimeInMillis(); 338 } 339 340 /** 341 * Handles changes to date range. 342 */ 343 public void onRangeChanged() { 344 mAdapter.setRange(mMinDate, mMaxDate); 345 346 // Changing the min/max date changes the selection position since we 347 // don't really have stable IDs. Jumps immediately to the new position. 348 setDate(mSelectedDay.getTimeInMillis(), false, false); 349 } 350 351 /** 352 * Sets the listener to call when the user selects a day. 353 * 354 * @param listener The listener to call. 355 */ 356 public void setOnDaySelectedListener(OnDaySelectedListener listener) { 357 mOnDaySelectedListener = listener; 358 } 359 360 private int getDiffMonths(Calendar start, Calendar end) { 361 final int diffYears = end.get(Calendar.YEAR) - start.get(Calendar.YEAR); 362 return end.get(Calendar.MONTH) - start.get(Calendar.MONTH) + 12 * diffYears; 363 } 364 365 private int getPositionFromDay(long timeInMillis) { 366 final int diffMonthMax = getDiffMonths(mMinDate, mMaxDate); 367 final int diffMonth = getDiffMonths(mMinDate, getTempCalendarForTime(timeInMillis)); 368 return MathUtils.constrain(diffMonth, 0, diffMonthMax); 369 } 370 371 private Calendar getTempCalendarForTime(long timeInMillis) { 372 if (mTempCalendar == null) { 373 mTempCalendar = Calendar.getInstance(); 374 } 375 mTempCalendar.setTimeInMillis(timeInMillis); 376 return mTempCalendar; 377 } 378 379 /** 380 * Gets the position of the view that is most prominently displayed within the list view. 381 */ 382 public int getMostVisiblePosition() { 383 return mViewPager.getCurrentItem(); 384 } 385 386 public void setPosition(int position) { 387 mViewPager.setCurrentItem(position, false); 388 } 389 390 private final OnPageChangeListener mOnPageChangedListener = new OnPageChangeListener() { 391 @Override 392 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 393 final float alpha = Math.abs(0.5f - positionOffset) * 2.0f; 394 mPrevButton.setAlpha(alpha); 395 mNextButton.setAlpha(alpha); 396 } 397 398 @Override 399 public void onPageScrollStateChanged(int state) {} 400 401 @Override 402 public void onPageSelected(int position) { 403 updateButtonVisibility(position); 404 } 405 }; 406 407 private final OnClickListener mOnClickListener = new OnClickListener() { 408 @Override 409 public void onClick(View v) { 410 final int direction; 411 if (v == mPrevButton) { 412 direction = -1; 413 } else if (v == mNextButton) { 414 direction = 1; 415 } else { 416 return; 417 } 418 419 // Animation is expensive for accessibility services since it sends 420 // lots of scroll and content change events. 421 final boolean animate = !mAccessibilityManager.isEnabled(); 422 423 // ViewPager clamps input values, so we don't need to worry 424 // about passing invalid indices. 425 final int nextItem = mViewPager.getCurrentItem() + direction; 426 mViewPager.setCurrentItem(nextItem, animate); 427 } 428 }; 429 430 public interface OnDaySelectedListener { 431 void onDaySelected(DayPickerView view, Calendar day); 432 } 433} 434