diff --git a/build.gradle b/build.gradle index 31280142..943e5b89 100644 --- a/build.gradle +++ b/build.gradle @@ -1,15 +1,21 @@ wrapper { //if you change this version you will need to run the 'gradlew wrapper' command twice from the command line to auto update the gradle cache - gradleVersion = "5.1.1" + gradleVersion = "6.5" } buildscript { + ext.kotlin_version = '1.4.10' + + ext.kotlin_version = "1.3.72" + repositories { google() jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:3.3.0' + classpath 'com.android.tools.build:gradle:4.1.1' classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 91ca28c8..62d4c053 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 1b1340d5..622ab64a 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ -distributionBase = GRADLE_USER_HOME -distributionPath = wrapper/dists -distributionUrl = https\://services.gradle.org/distributions/gradle-5.1.1-bin.zip -zipStoreBase = GRADLE_USER_HOME -zipStorePath = wrapper/dists +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index cccdd3d5..fbd7c515 100755 --- a/gradlew +++ b/gradlew @@ -1,5 +1,21 @@ #!/usr/bin/env sh +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + ############################################################################## ## ## Gradle start up script for UN*X @@ -28,7 +44,7 @@ APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" @@ -66,6 +82,7 @@ esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then @@ -109,10 +126,11 @@ if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath @@ -138,19 +156,19 @@ if $cygwin ; then else eval `echo args$i`="\"$arg\"" fi - i=$((i+1)) + i=`expr $i + 1` done case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi @@ -159,14 +177,9 @@ save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } -APP_ARGS=$(save "$@") +APP_ARGS=`save "$@"` # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index e95643d6..a9f778a7 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,3 +1,19 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @@ -13,8 +29,11 @@ if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome @@ -65,6 +84,7 @@ set CMD_LINE_ARGS=%* set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% diff --git a/library/build.gradle b/library/build.gradle index 824727a5..fd587f96 100644 --- a/library/build.gradle +++ b/library/build.gradle @@ -1,6 +1,8 @@ apply plugin: 'com.android.library' apply plugin: 'maven' apply plugin: 'com.github.dcendents.android-maven' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-android-extensions' android { compileSdkVersion rootProject.ext.compileSdkVersion @@ -37,6 +39,7 @@ dependencies { rootProject.ext.testDep.each { testImplementation it } rootProject.ext.androidTestDep.each { androidTestImplementation it } + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" } tasks.withType(Javadoc) { @@ -60,4 +63,7 @@ android.libraryVariants.all { variant -> linksOffline "http://d.android.com/reference", "${android.sdkDirectory}/docs/reference" } } +} +repositories { + mavenCentral() } \ No newline at end of file diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/AnimatorListener.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/AnimatorListener.java deleted file mode 100644 index cf9ee34d..00000000 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/AnimatorListener.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.prolificinteractive.materialcalendarview; - -import android.animation.Animator; - -class AnimatorListener implements Animator.AnimatorListener { - @Override - public void onAnimationStart(Animator animator) { - } - - @Override - public void onAnimationEnd(Animator animator) { - } - - @Override - public void onAnimationCancel(Animator animator) { - } - - @Override - public void onAnimationRepeat(Animator animator) { - } -} diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java deleted file mode 100644 index 4a0b073d..00000000 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.java +++ /dev/null @@ -1,186 +0,0 @@ -package com.prolificinteractive.materialcalendarview; - -import android.os.Parcel; -import android.os.Parcelable; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import org.threeten.bp.LocalDate; - -/** - * An imputable representation of a day on a calendar, based on {@link LocalDate}. - */ -public final class CalendarDay implements Parcelable { - - /** - * Everything is based on this variable for {@link CalendarDay}. - */ - @NonNull private final LocalDate date; - - /** - * @param year new instance's year - * @param month new instance's month as defined by {@linkplain java.util.Calendar} - * @param day new instance's day of month - */ - private CalendarDay(final int year, final int month, final int day) { - date = LocalDate.of(year, month, day); - } - - /** - * @param date {@link LocalDate} instance - */ - private CalendarDay(@NonNull final LocalDate date) { - this.date = date; - } - - /** - * Get a new instance set to today - * - * @return CalendarDay set to today's date - */ - @NonNull public static CalendarDay today() { - return from(LocalDate.now()); - } - - /** - * Get a new instance set to the specified day - * - * @param year new instance's year - * @param month new instance's month as defined by {@linkplain java.util.Calendar} - * @param day new instance's day of month - * @return CalendarDay set to the specified date - */ - @NonNull public static CalendarDay from(int year, int month, int day) { - return new CalendarDay(year, month, day); - } - - /** - * Get a new instance set to the specified day - * - * @param date {@linkplain LocalDate} to pull date information from. Passing null will return null - * @return CalendarDay set to the specified date - */ - public static CalendarDay from(@Nullable LocalDate date) { - if (date == null) { - return null; - } - return new CalendarDay(date); - } - - /** - * Get the year - * - * @return the year for this day - */ - public int getYear() { - return date.getYear(); - } - - /** - * Get the month, represented by values from {@linkplain LocalDate} - * - * @return the month of the year as defined by {@linkplain LocalDate} - */ - public int getMonth() { - return date.getMonthValue(); - } - - /** - * Get the day - * - * @return the day of the month for this day - */ - public int getDay() { - return date.getDayOfMonth(); - } - - /** - * Get this day as a {@linkplain LocalDate} - * - * @return a date with this days information - */ - @NonNull public LocalDate getDate() { - return date; - } - - /** - * Determine if this day is within a specified range - * - * @param minDate the earliest day, may be null - * @param maxDate the latest day, may be null - * @return true if the between (inclusive) the min and max dates. - */ - public boolean isInRange(@Nullable CalendarDay minDate, @Nullable CalendarDay maxDate) { - return !(minDate != null && minDate.isAfter(this)) && - !(maxDate != null && maxDate.isBefore(this)); - } - - /** - * Determine if this day is before the given instance - * - * @param other the other day to test - * @return true if this is before other, false if equal or after - */ - public boolean isBefore(@NonNull final CalendarDay other) { - return date.isBefore(other.getDate()); - } - - /** - * Determine if this day is after the given instance - * - * @param other the other day to test - * @return true if this is after other, false if equal or before - */ - public boolean isAfter(@NonNull final CalendarDay other) { - return date.isAfter(other.getDate()); - } - - @Override public boolean equals(Object o) { - return o instanceof CalendarDay && date.equals(((CalendarDay) o).getDate()); - } - - @Override - public int hashCode() { - return hashCode(date.getYear(), date.getMonthValue(), date.getDayOfMonth()); - } - - private static int hashCode(int year, int month, int day) { - //Should produce hashes like "20150401" - return (year * 10000) + (month * 100) + day; - } - - @Override - public String toString() { - return "CalendarDay{" + date.getYear() + "-" + date.getMonthValue() + "-" - + date.getDayOfMonth() + "}"; - } - - /* - * Parcelable Stuff - */ - - public CalendarDay(Parcel in) { - this(in.readInt(), in.readInt(), in.readInt()); - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeInt(date.getYear()); - dest.writeInt(date.getMonthValue()); - dest.writeInt(date.getDayOfMonth()); - } - - public static final Creator CREATOR = new Creator() { - public CalendarDay createFromParcel(Parcel in) { - return new CalendarDay(in); - } - - public CalendarDay[] newArray(int size) { - return new CalendarDay[size]; - } - }; -} diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.kt b/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.kt new file mode 100644 index 00000000..44fc5654 --- /dev/null +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarDay.kt @@ -0,0 +1,162 @@ +package com.prolificinteractive.materialcalendarview + +import android.os.Parcel +import android.os.Parcelable +import org.threeten.bp.LocalDate + +class CalendarDay +/** + * @param date [LocalDate] instance + */ +private constructor( + /** + * Everything is based on this variable for [CalendarDay]. + */ + var date: LocalDate +) : Parcelable { + + /** + * @param year new instance's year + * @param month new instance's month as defined by [java.util.Calendar] + * @param day new instance's day of month + */ + private constructor(year: Int, month: Int, day: Int) : this(LocalDate.of(year, month, day)) + + val year: Int + /** + * Get the year + * + * @return the year for this day + */ + get() = date.year + + + val month: Int + /** + * Get the month, represented by values from {@linkplain LocalDate} + * + * @return the month of the year as defined by {@linkplain LocalDate} + */ + get() = date.monthValue + + + val day: Int + /** + * Get the day + * + * @return the day of the month for this day + */ + get() = date.dayOfMonth + + constructor(parcel: Parcel) : this(parcel.readInt(), parcel.readInt(), parcel.readInt()) + + /** + * Determine if this day is within a specified range + * + * @param minDate the earliest day, may be null + * @param maxDate the latest day, may be null + * @return true if the between (inclusive) the min and max dates. + */ + + fun isInRange(minDate: CalendarDay?, maxDate: CalendarDay?): Boolean { + return !(minDate != null && minDate.isAfter(this)) && + !(maxDate != null && maxDate.isBefore(this)) + } + + + /** + * Determine if this day is before the given instance + * + * @param other the other day to test + * @return true if this is before other, false if equal or after + */ + infix fun isBefore(other: CalendarDay): Boolean { + return date.isBefore(other.date) + } + + /** + * Determine if this day is after the given instance + * + * @param other the other day to test + * @return true if this is after other, false if equal or before + */ + infix fun isAfter(other: CalendarDay): Boolean { + return date.isAfter(other.date) + } + + override fun equals(other: Any?): Boolean { + return other is CalendarDay && date == other.date + } + + override fun hashCode(): Int = hashCode(date.year, date.monthValue, date.dayOfMonth) + + override fun toString(): String { + return ("CalendarDay{" + date.year + "-" + date.monthValue + "-" + date.dayOfMonth + "}") + } + + + companion object { + + /** + * Get a new instance set to today + * + * @return CalendarDay set to today's date + */ + @JvmStatic + fun today(): CalendarDay? { + return from(LocalDate.now()) + } + + /** + * Get a new instance set to the specified day + * + * @param year new instance's year + * @param month new instance's month as defined by [java.util.Calendar] + * @param day new instance's day of month + * @return CalendarDay set to the specified date + */ + @JvmStatic + fun from(year: Int, month: Int, day: Int): CalendarDay { + return CalendarDay(year, month, day) + } + + /** + * Get a new instance set to the specified day + * + * @param date [LocalDate] to pull date information from. Passing null will return null + * @return CalendarDay set to the specified date + */ + @JvmStatic + fun from(date: LocalDate?): CalendarDay? { + return date?.let { + CalendarDay(date) + } + } + + @JvmStatic + private fun hashCode(year: Int, month: Int, day: Int): Int { + //Should produce hashes like "20150401" + return year * 10000 + month * 100 + day + } + + @JvmStatic + val CREATOR = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): CalendarDay { + return CalendarDay(parcel) + } + + override fun newArray(size: Int): Array { + return arrayOfNulls(size) + } + } + } + + override fun writeToParcel(dest: Parcel, flags: Int) { + dest.writeInt(date.year) + dest.writeInt(date.monthValue) + dest.writeInt(date.dayOfMonth) + } + + override fun describeContents(): Int = 0 + +} \ No newline at end of file diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarMode.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarMode.java deleted file mode 100644 index 3c704ad8..00000000 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarMode.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.prolificinteractive.materialcalendarview; - -/** - * Different Calendar types available for the pager, which will give the amount of weeks visible. - */ -public enum CalendarMode { - - /** - * Month Mode to display an entire month per page. - */ - MONTHS(6), - /** - * Week mode that shows the calendar week by week. - */ - WEEKS(1); - - /** - * Number of visible weeks per calendar mode. - */ - final int visibleWeeksCount; - - CalendarMode(int visibleWeeksCount) { - this.visibleWeeksCount = visibleWeeksCount; - } -} diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarMode.kt b/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarMode.kt new file mode 100644 index 00000000..eb92cd03 --- /dev/null +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarMode.kt @@ -0,0 +1,23 @@ +package com.prolificinteractive.materialcalendarview + + +/** + * Different Calendar types available for the pager, which will give the amount of weeks visible. + */ +enum class CalendarMode( + /** + * Number of visible weeks per calendar mode. + */ + val visibleWeeksCount: Int +) { + + /** + * Month Mode to display an entire month per page. + */ + MONTHS(6), + + /** + * Week mode that shows the calendar week by week. + */ + WEEKS(1) +} \ No newline at end of file diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerAdapter.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerAdapter.java index d4c68eae..27ce3217 100644 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerAdapter.java +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerAdapter.java @@ -5,14 +5,19 @@ import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; + import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import com.prolificinteractive.materialcalendarview.format.TitleFormatter; import com.prolificinteractive.materialcalendarview.format.WeekDayFormatter; +import com.prolificinteractive.materialcalendarview.listeners.DateRangeIndex; +import com.prolificinteractive.materialcalendarview.listeners.DayViewDecorator; + import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.List; + import org.threeten.bp.LocalDate; /** @@ -20,359 +25,360 @@ */ abstract class CalendarPagerAdapter extends PagerAdapter { - private final ArrayDeque currentViews; - - protected final MaterialCalendarView mcv; - private final CalendarDay today; - - @NonNull private TitleFormatter titleFormatter = TitleFormatter.DEFAULT; - private Integer color = null; - private Integer dateTextAppearance = null; - private Integer weekDayTextAppearance = null; - @ShowOtherDates - private int showOtherDates = MaterialCalendarView.SHOW_DEFAULTS; - private CalendarDay minDate = null; - private CalendarDay maxDate = null; - private DateRangeIndex rangeIndex; - private List selectedDates = new ArrayList<>(); - private WeekDayFormatter weekDayFormatter = WeekDayFormatter.DEFAULT; - private DayFormatter dayFormatter = DayFormatter.DEFAULT; - private DayFormatter dayFormatterContentDescription = dayFormatter; - private List decorators = new ArrayList<>(); - private List decoratorResults = null; - private boolean selectionEnabled = true; - boolean showWeekDays; - - CalendarPagerAdapter(MaterialCalendarView mcv) { - this.mcv = mcv; - this.today = CalendarDay.today(); - currentViews = new ArrayDeque<>(); - currentViews.iterator(); - setRangeDates(null, null); - } - - public void setDecorators(List decorators) { - this.decorators = decorators; - invalidateDecorators(); - } - - public void invalidateDecorators() { - decoratorResults = new ArrayList<>(); - for (DayViewDecorator decorator : decorators) { - DayViewFacade facade = new DayViewFacade(); - decorator.decorate(facade); - if (facade.isDecorated()) { - decoratorResults.add(new DecoratorResult(decorator, facade)); - } - } - for (V pagerView : currentViews) { - pagerView.setDayViewDecorators(decoratorResults); - } - } - - @Override - public int getCount() { - return rangeIndex.getCount(); - } - - @Override - public CharSequence getPageTitle(int position) { - return titleFormatter.format(getItem(position)); - } - - public CalendarPagerAdapter migrateStateAndReturn(CalendarPagerAdapter newAdapter) { - newAdapter.titleFormatter = titleFormatter; - newAdapter.color = color; - newAdapter.dateTextAppearance = dateTextAppearance; - newAdapter.weekDayTextAppearance = weekDayTextAppearance; - newAdapter.showOtherDates = showOtherDates; - newAdapter.minDate = minDate; - newAdapter.maxDate = maxDate; - newAdapter.selectedDates = selectedDates; - newAdapter.weekDayFormatter = weekDayFormatter; - newAdapter.dayFormatter = dayFormatter; - newAdapter.dayFormatterContentDescription = dayFormatterContentDescription; - newAdapter.decorators = decorators; - newAdapter.decoratorResults = decoratorResults; - newAdapter.selectionEnabled = selectionEnabled; - return newAdapter; - } - - public int getIndexForDay(CalendarDay day) { - if (day == null) { - return getCount() / 2; - } - if (minDate != null && day.isBefore(minDate)) { - return 0; - } - if (maxDate != null && day.isAfter(maxDate)) { - return getCount() - 1; - } - return rangeIndex.indexOf(day); - } - - protected abstract V createView(int position); - - protected abstract int indexOf(V view); - - protected abstract boolean isInstanceOfView(Object object); - - protected abstract DateRangeIndex createRangeIndex(CalendarDay min, CalendarDay max); - - @Override - public int getItemPosition(@NonNull Object object) { - if (!(isInstanceOfView(object))) { - return POSITION_NONE; - } - CalendarPagerView pagerView = (CalendarPagerView) object; - CalendarDay firstViewDay = pagerView.getFirstViewDay(); - if (firstViewDay == null) { - return POSITION_NONE; - } - int index = indexOf((V) object); - if (index < 0) { - return POSITION_NONE; - } - return index; - } - - @NonNull - @Override - public Object instantiateItem(@NonNull ViewGroup container, int position) { - V pagerView = createView(position); - pagerView.setContentDescription(mcv.getCalendarContentDescription()); - pagerView.setAlpha(0); - pagerView.setSelectionEnabled(selectionEnabled); - - pagerView.setWeekDayFormatter(weekDayFormatter); - pagerView.setDayFormatter(dayFormatter); - pagerView.setDayFormatterContentDescription(dayFormatterContentDescription); - if (color != null) { - pagerView.setSelectionColor(color); - } - if (dateTextAppearance != null) { - pagerView.setDateTextAppearance(dateTextAppearance); - } - if (weekDayTextAppearance != null) { - pagerView.setWeekDayTextAppearance(weekDayTextAppearance); - } - pagerView.setShowOtherDates(showOtherDates); - pagerView.setMinimumDate(minDate); - pagerView.setMaximumDate(maxDate); - pagerView.setSelectedDates(selectedDates); - - container.addView(pagerView); - currentViews.add(pagerView); + private final ArrayDeque currentViews; + + protected final MaterialCalendarView mcv; + private final CalendarDay today; + + @NonNull + private TitleFormatter titleFormatter = TitleFormatter.DEFAULT; + private Integer color = null; + private Integer dateTextAppearance = null; + private Integer weekDayTextAppearance = null; + @ShowOtherDates + private int showOtherDates = MaterialCalendarView.SHOW_DEFAULTS; + private CalendarDay minDate = null; + private CalendarDay maxDate = null; + private DateRangeIndex rangeIndex; + private List selectedDates = new ArrayList<>(); + private WeekDayFormatter weekDayFormatter = WeekDayFormatter.DEFAULT; + private DayFormatter dayFormatter = DayFormatter.DEFAULT; + private DayFormatter dayFormatterContentDescription = dayFormatter; + private List decorators = new ArrayList<>(); + private List decoratorResults = null; + private boolean selectionEnabled = true; + boolean showWeekDays; + + CalendarPagerAdapter(MaterialCalendarView mcv) { + this.mcv = mcv; + this.today = CalendarDay.today(); + currentViews = new ArrayDeque<>(); + currentViews.iterator(); + setRangeDates(null, null); + } - pagerView.setDayViewDecorators(decoratorResults); - - return pagerView; - } - - public void setShowWeekDays(boolean showWeekDays) { - this.showWeekDays = showWeekDays; - } + public void setDecorators(List decorators) { + this.decorators = decorators; + invalidateDecorators(); + } - public boolean isShowWeekDays() { - return showWeekDays; - } + public void invalidateDecorators() { + decoratorResults = new ArrayList<>(); + for (DayViewDecorator decorator : decorators) { + DayViewFacade facade = new DayViewFacade(); + decorator.decorate(facade); + if (facade.isDecorated()) { + decoratorResults.add(new DecoratorResult(decorator, facade)); + } + } + for (V pagerView : currentViews) { + pagerView.setDayViewDecorators(decoratorResults); + } + } - public void setSelectionEnabled(boolean enabled) { - selectionEnabled = enabled; - for (V pagerView : currentViews) { - pagerView.setSelectionEnabled(selectionEnabled); + @Override + public int getCount() { + return rangeIndex.getCount(); } - } - @Override - public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { - V pagerView = (V) object; - currentViews.remove(pagerView); - container.removeView(pagerView); - } + @Override + public CharSequence getPageTitle(int position) { + return titleFormatter.format(getItem(position)); + } - @Override - public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { - return view == object; - } + public CalendarPagerAdapter migrateStateAndReturn(CalendarPagerAdapter newAdapter) { + newAdapter.titleFormatter = titleFormatter; + newAdapter.color = color; + newAdapter.dateTextAppearance = dateTextAppearance; + newAdapter.weekDayTextAppearance = weekDayTextAppearance; + newAdapter.showOtherDates = showOtherDates; + newAdapter.minDate = minDate; + newAdapter.maxDate = maxDate; + newAdapter.selectedDates = selectedDates; + newAdapter.weekDayFormatter = weekDayFormatter; + newAdapter.dayFormatter = dayFormatter; + newAdapter.dayFormatterContentDescription = dayFormatterContentDescription; + newAdapter.decorators = decorators; + newAdapter.decoratorResults = decoratorResults; + newAdapter.selectionEnabled = selectionEnabled; + return newAdapter; + } - public void setTitleFormatter(@Nullable TitleFormatter titleFormatter) { - this.titleFormatter = titleFormatter == null ? TitleFormatter.DEFAULT : titleFormatter; - } + public int getIndexForDay(CalendarDay day) { + if (day == null) { + return getCount() / 2; + } + if (minDate != null && day.isBefore(minDate)) { + return 0; + } + if (maxDate != null && day.isAfter(maxDate)) { + return getCount() - 1; + } + return rangeIndex.indexOf(day); + } + + protected abstract V createView(int position); + + protected abstract int indexOf(V view); + + protected abstract boolean isInstanceOfView(Object object); + + protected abstract DateRangeIndex createRangeIndex(CalendarDay min, CalendarDay max); + + @Override + public int getItemPosition(@NonNull Object object) { + if (!(isInstanceOfView(object))) { + return POSITION_NONE; + } + CalendarPagerView pagerView = (CalendarPagerView) object; + CalendarDay firstViewDay = pagerView.getFirstViewDay(); + if (firstViewDay == null) { + return POSITION_NONE; + } + int index = indexOf((V) object); + if (index < 0) { + return POSITION_NONE; + } + return index; + } + + @NonNull + @Override + public Object instantiateItem(@NonNull ViewGroup container, int position) { + V pagerView = createView(position); + pagerView.setContentDescription(mcv.getCalendarContentDescription()); + pagerView.setAlpha(0); + pagerView.setSelectionEnabled(selectionEnabled); + + pagerView.setWeekDayFormatter(weekDayFormatter); + pagerView.setDayFormatter(dayFormatter); + pagerView.setDayFormatterContentDescription(dayFormatterContentDescription); + if (color != null) { + pagerView.setSelectionColor(color); + } + if (dateTextAppearance != null) { + pagerView.setDateTextAppearance(dateTextAppearance); + } + if (weekDayTextAppearance != null) { + pagerView.setWeekDayTextAppearance(weekDayTextAppearance); + } + pagerView.setShowOtherDates(showOtherDates); + pagerView.setMinimumDate(minDate); + pagerView.setMaximumDate(maxDate); + pagerView.setSelectedDates(selectedDates); + + container.addView(pagerView); + currentViews.add(pagerView); + + pagerView.setDayViewDecorators(decoratorResults); + + return pagerView; + } + + public void setShowWeekDays(boolean showWeekDays) { + this.showWeekDays = showWeekDays; + } - public void setSelectionColor(int color) { - this.color = color; - for (V pagerView : currentViews) { - pagerView.setSelectionColor(color); + public boolean isShowWeekDays() { + return showWeekDays; } - } - public void setDateTextAppearance(int taId) { - if (taId == 0) { - return; + public void setSelectionEnabled(boolean enabled) { + selectionEnabled = enabled; + for (V pagerView : currentViews) { + pagerView.setSelectionEnabled(selectionEnabled); + } } - this.dateTextAppearance = taId; - for (V pagerView : currentViews) { - pagerView.setDateTextAppearance(taId); + + @Override + public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { + V pagerView = (V) object; + currentViews.remove(pagerView); + container.removeView(pagerView); } - } - public void setShowOtherDates(@ShowOtherDates int showFlags) { - this.showOtherDates = showFlags; - for (V pagerView : currentViews) { - pagerView.setShowOtherDates(showFlags); + @Override + public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { + return view == object; } - } - public void setWeekDayFormatter(WeekDayFormatter formatter) { - this.weekDayFormatter = formatter; - for (V pagerView : currentViews) { - pagerView.setWeekDayFormatter(formatter); + public void setTitleFormatter(@Nullable TitleFormatter titleFormatter) { + this.titleFormatter = titleFormatter == null ? TitleFormatter.DEFAULT : titleFormatter; } - } - public void setDayFormatter(DayFormatter formatter) { - dayFormatterContentDescription = dayFormatterContentDescription == dayFormatter ? - formatter : dayFormatterContentDescription; - this.dayFormatter = formatter; - for (V pagerView : currentViews) { - pagerView.setDayFormatter(formatter); + public void setSelectionColor(int color) { + this.color = color; + for (V pagerView : currentViews) { + pagerView.setSelectionColor(color); + } } - } - public void setDayFormatterContentDescription(DayFormatter formatter) { - dayFormatterContentDescription = formatter; - for (V pagerView : currentViews) { - pagerView.setDayFormatterContentDescription(formatter); + public void setDateTextAppearance(int taId) { + if (taId == 0) { + return; + } + this.dateTextAppearance = taId; + for (V pagerView : currentViews) { + pagerView.setDateTextAppearance(taId); + } } - } - @ShowOtherDates - public int getShowOtherDates() { - return showOtherDates; - } + public void setShowOtherDates(@ShowOtherDates int showFlags) { + this.showOtherDates = showFlags; + for (V pagerView : currentViews) { + pagerView.setShowOtherDates(showFlags); + } + } - public void setWeekDayTextAppearance(int taId) { - if (taId == 0) { - return; + public void setWeekDayFormatter(WeekDayFormatter formatter) { + this.weekDayFormatter = formatter; + for (V pagerView : currentViews) { + pagerView.setWeekDayFormatter(formatter); + } } - this.weekDayTextAppearance = taId; - for (V pagerView : currentViews) { - pagerView.setWeekDayTextAppearance(taId); + + public void setDayFormatter(DayFormatter formatter) { + dayFormatterContentDescription = dayFormatterContentDescription == dayFormatter ? + formatter : dayFormatterContentDescription; + this.dayFormatter = formatter; + for (V pagerView : currentViews) { + pagerView.setDayFormatter(formatter); + } } - } - public void setRangeDates(CalendarDay min, CalendarDay max) { - this.minDate = min; - this.maxDate = max; - for (V pagerView : currentViews) { - pagerView.setMinimumDate(min); - pagerView.setMaximumDate(max); + public void setDayFormatterContentDescription(DayFormatter formatter) { + dayFormatterContentDescription = formatter; + for (V pagerView : currentViews) { + pagerView.setDayFormatterContentDescription(formatter); + } } - if (min == null) { - min = CalendarDay.from(today.getYear() - 200, today.getMonth(), today.getDay()); + @ShowOtherDates + public int getShowOtherDates() { + return showOtherDates; } - if (max == null) { - max = CalendarDay.from(today.getYear() + 200, today.getMonth(), today.getDay()); + public void setWeekDayTextAppearance(int taId) { + if (taId == 0) { + return; + } + this.weekDayTextAppearance = taId; + for (V pagerView : currentViews) { + pagerView.setWeekDayTextAppearance(taId); + } } - rangeIndex = createRangeIndex(min, max); + public void setRangeDates(CalendarDay min, CalendarDay max) { + this.minDate = min; + this.maxDate = max; + for (V pagerView : currentViews) { + pagerView.setMinimumDate(min); + pagerView.setMaximumDate(max); + } - notifyDataSetChanged(); - invalidateSelectedDates(); - } + if (min == null) { + min = CalendarDay.from(today.getYear() - 200, today.getMonth(), today.getDay()); + } - public DateRangeIndex getRangeIndex() { - return rangeIndex; - } + if (max == null) { + max = CalendarDay.from(today.getYear() + 200, today.getMonth(), today.getDay()); + } - public void clearSelections() { - selectedDates.clear(); - invalidateSelectedDates(); - } + rangeIndex = createRangeIndex(min, max); - /** - * Select or un-select a day. - * - * @param day Day to select or un-select - * @param selected Whether to select or un-select the day from the list. - * @see CalendarPagerAdapter#selectRange(CalendarDay, CalendarDay) - */ - public void setDateSelected(CalendarDay day, boolean selected) { - if (selected) { - if (!selectedDates.contains(day)) { - selectedDates.add(day); + notifyDataSetChanged(); invalidateSelectedDates(); - } - } else { - if (selectedDates.contains(day)) { - selectedDates.remove(day); + } + + public DateRangeIndex getRangeIndex() { + return rangeIndex; + } + + public void clearSelections() { + selectedDates.clear(); invalidateSelectedDates(); - } } - } - /** - * Clear the previous selection, select the range of days from first to last, and finally - * invalidate. First day should be before last day, otherwise the selection won't happen. - * - * @param first The first day of the range. - * @param last The last day in the range. - * @see CalendarPagerAdapter#setDateSelected(CalendarDay, boolean) - */ - public void selectRange(final CalendarDay first, final CalendarDay last) { - selectedDates.clear(); + /** + * Select or un-select a day. + * + * @param day Day to select or un-select + * @param selected Whether to select or un-select the day from the list. + * @see CalendarPagerAdapter#selectRange(CalendarDay, CalendarDay) + */ + public void setDateSelected(CalendarDay day, boolean selected) { + if (selected) { + if (!selectedDates.contains(day)) { + selectedDates.add(day); + invalidateSelectedDates(); + } + } else { + if (selectedDates.contains(day)) { + selectedDates.remove(day); + invalidateSelectedDates(); + } + } + } - // Copy to start from the first day and increment - LocalDate temp = LocalDate.of(first.getYear(), first.getMonth(), first.getDay()); + /** + * Clear the previous selection, select the range of days from first to last, and finally + * invalidate. First day should be before last day, otherwise the selection won't happen. + * + * @param first The first day of the range. + * @param last The last day in the range. + * @see CalendarPagerAdapter#setDateSelected(CalendarDay, boolean) + */ + public void selectRange(final CalendarDay first, final CalendarDay last) { + selectedDates.clear(); - // for comparison - final LocalDate end = last.getDate(); + // Copy to start from the first day and increment + LocalDate temp = LocalDate.of(first.getYear(), first.getMonth(), first.getDay()); - while( temp.isBefore(end) || temp.equals(end) ) { - selectedDates.add(CalendarDay.from(temp)); - temp = temp.plusDays(1); - } + // for comparison + final LocalDate end = last.getDate(); - invalidateSelectedDates(); - } + while (temp.isBefore(end) || temp.equals(end)) { + selectedDates.add(CalendarDay.from(temp)); + temp = temp.plusDays(1); + } - private void invalidateSelectedDates() { - validateSelectedDates(); - for (V pagerView : currentViews) { - pagerView.setSelectedDates(selectedDates); + invalidateSelectedDates(); } - } - private void validateSelectedDates() { - for (int i = 0; i < selectedDates.size(); i++) { - CalendarDay date = selectedDates.get(i); + private void invalidateSelectedDates() { + validateSelectedDates(); + for (V pagerView : currentViews) { + pagerView.setSelectedDates(selectedDates); + } + } - if ((minDate != null && minDate.isAfter(date)) || (maxDate != null - && maxDate.isBefore(date))) { - selectedDates.remove(i); - mcv.onDateUnselected(date); - i -= 1; - } + private void validateSelectedDates() { + for (int i = 0; i < selectedDates.size(); i++) { + CalendarDay date = selectedDates.get(i); + + if ((minDate != null && minDate.isAfter(date)) || (maxDate != null + && maxDate.isBefore(date))) { + selectedDates.remove(i); + mcv.onDateUnselected(date); + i -= 1; + } + } } - } - public CalendarDay getItem(int position) { - return rangeIndex.getItem(position); - } + public CalendarDay getItem(int position) { + return rangeIndex.getItem(position); + } - @NonNull - public List getSelectedDates() { - return Collections.unmodifiableList(selectedDates); - } + @NonNull + public List getSelectedDates() { + return Collections.unmodifiableList(selectedDates); + } - protected int getDateTextAppearance() { - return dateTextAppearance == null ? 0 : dateTextAppearance; - } + protected int getDateTextAppearance() { + return dateTextAppearance == null ? 0 : dateTextAppearance; + } - protected int getWeekDayTextAppearance() { - return weekDayTextAppearance == null ? 0 : weekDayTextAppearance; - } + protected int getWeekDayTextAppearance() { + return weekDayTextAppearance == null ? 0 : weekDayTextAppearance; + } } diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerView.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerView.java index f3a4fa9a..9eccf7c2 100644 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerView.java +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/CalendarPagerView.java @@ -1,18 +1,23 @@ package com.prolificinteractive.materialcalendarview; +import android.content.Context; import android.os.Build; import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; + import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import com.prolificinteractive.materialcalendarview.format.WeekDayFormatter; + import java.util.ArrayList; import java.util.Collection; import java.util.List; + import org.threeten.bp.DayOfWeek; import org.threeten.bp.LocalDate; import org.threeten.bp.temporal.TemporalField; @@ -22,348 +27,372 @@ import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showOtherMonths; abstract class CalendarPagerView extends ViewGroup - implements View.OnClickListener, View.OnLongClickListener { - - protected static final int DEFAULT_DAYS_IN_WEEK = 7; - protected static final int DEFAULT_MAX_WEEKS = 6; - protected static final int DAY_NAMES_ROW = 1; - - private final ArrayList weekDayViews = new ArrayList<>(); - private final ArrayList decoratorResults = new ArrayList<>(); - private final DayOfWeek firstDayOfWeek; - @ShowOtherDates protected int showOtherDates = SHOW_DEFAULTS; - private MaterialCalendarView mcv; - private CalendarDay firstViewDay; - private CalendarDay minDate = null; - private CalendarDay maxDate = null; - protected boolean showWeekDays; - - private final Collection dayViews = new ArrayList<>(); - - public CalendarPagerView( - @NonNull MaterialCalendarView view, - CalendarDay firstViewDay, - DayOfWeek firstDayOfWeek, - boolean showWeekDays) { - super(view.getContext()); - - this.mcv = view; - this.firstViewDay = firstViewDay; - this.firstDayOfWeek = firstDayOfWeek; - this.showWeekDays = showWeekDays; - - setClipChildren(false); - setClipToPadding(false); - - if (showWeekDays) { - buildWeekDays(resetAndGetWorkingCalendar()); - } - buildDayViews(dayViews, resetAndGetWorkingCalendar()); - } + implements View.OnClickListener, View.OnLongClickListener { + + protected static final int DEFAULT_DAYS_IN_WEEK = 7; + protected static final int DEFAULT_MAX_WEEKS = 6; + protected static final int DAY_NAMES_ROW = 1; + + private final ArrayList weekDayViews = new ArrayList<>(); + private final ArrayList decoratorResults = new ArrayList<>(); + private DayOfWeek firstDayOfWeek; + @ShowOtherDates + protected int showOtherDates = SHOW_DEFAULTS; + private MaterialCalendarView mcv; + private CalendarDay firstViewDay; + private CalendarDay minDate = null; + private CalendarDay maxDate = null; + protected boolean showWeekDays; + + private final Collection dayViews = new ArrayList<>(); + + + CalendarPagerView(Context context) { + super(context); + } + + CalendarPagerView(Context context, AttributeSet attributeSet) { + super(context, attributeSet); + } + + public CalendarPagerView( + @NonNull MaterialCalendarView view, + @Nullable CalendarDay firstViewDay, + @Nullable DayOfWeek firstDayOfWeek, + boolean showWeekDays) { + super(view.getContext()); + + this.mcv = view; + this.firstViewDay = firstViewDay; + this.firstDayOfWeek = firstDayOfWeek; + this.showWeekDays = showWeekDays; + + setClipChildren(false); + setClipToPadding(false); + + if (showWeekDays) { + buildWeekDays(resetAndGetWorkingCalendar()); + } + buildDayViews(dayViews, resetAndGetWorkingCalendar()); + } + + private void buildWeekDays(@Nullable LocalDate calendar) { + if (calendar != null) { + LocalDate local = calendar; + for (int i = 0; i < DEFAULT_DAYS_IN_WEEK; i++) { + WeekDayView weekDayView = new WeekDayView(getContext(), local.getDayOfWeek()); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { + weekDayView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); + } + weekDayViews.add(weekDayView); + addView(weekDayView); + local = local.plusDays(1); + } + } + } + + protected void addDayView(Collection dayViews, LocalDate temp) { + CalendarDay day = CalendarDay.from(temp); + DayView dayView = new DayView(getContext(), day); + dayView.setOnClickListener(this); + dayView.setOnLongClickListener(this); + dayViews.add(dayView); + addView(dayView, new LayoutParams()); + } + + protected LocalDate resetAndGetWorkingCalendar() { + final TemporalField firstDayOfWeek = WeekFields.of(this.firstDayOfWeek, 1).dayOfWeek(); + final CalendarDay firstViewDay = getFirstViewDay(); + + if (firstViewDay != null) { + final LocalDate temp = getFirstViewDay().getDate().with(firstDayOfWeek, 1); + int dow = temp.getDayOfWeek().getValue(); + int delta = getFirstDayOfWeek().getValue() - dow; + boolean removeRow = showOtherMonths(showOtherDates) ? delta >= 0 : delta > 0; + if (removeRow) { + delta -= DEFAULT_DAYS_IN_WEEK; + } + + return temp.plusDays(delta); + } + + + //If the delta is positive, we want to remove a week + + return null; + + } + + protected DayOfWeek getFirstDayOfWeek() { + return firstDayOfWeek; + } + + protected abstract void buildDayViews(Collection dayViews, LocalDate calendar); + + protected abstract boolean isDayEnabled(CalendarDay day); + + void setDayViewDecorators(List results) { + this.decoratorResults.clear(); + if (results != null) { + this.decoratorResults.addAll(results); + } + invalidateDecorators(); + } + + public void setWeekDayTextAppearance(int taId) { + for (WeekDayView weekDayView : weekDayViews) { + weekDayView.setTextAppearance(getContext(), taId); + } + } + + public void setDateTextAppearance(int taId) { + for (DayView dayView : dayViews) { + dayView.setTextAppearance(getContext(), taId); + } + } + + public void setShowOtherDates(@ShowOtherDates int showFlags) { + this.showOtherDates = showFlags; + updateUi(); + } + + public void setSelectionEnabled(boolean selectionEnabled) { + for (DayView dayView : dayViews) { + dayView.setOnClickListener(selectionEnabled ? this : null); + dayView.setClickable(selectionEnabled); + } + } + + public void setSelectionColor(int color) { + for (DayView dayView : dayViews) { + dayView.setSelectionColor(color); + } + } + + public void setWeekDayFormatter(WeekDayFormatter formatter) { + for (WeekDayView dayView : weekDayViews) { + dayView.setWeekDayFormatter(formatter); + } + } + + public void setDayFormatter(DayFormatter formatter) { + for (DayView dayView : dayViews) { + dayView.setDayFormatter(formatter); + } + } + + public void setDayFormatterContentDescription(DayFormatter formatter) { + for (DayView dayView : dayViews) { + dayView.setDayFormatterContentDescription(formatter); + } + } + + public void setMinimumDate(CalendarDay minDate) { + this.minDate = minDate; + updateUi(); + } + + public void setMaximumDate(CalendarDay maxDate) { + this.maxDate = maxDate; + updateUi(); + } + + public void setSelectedDates(Collection dates) { + for (DayView dayView : dayViews) { + CalendarDay day = dayView.getDate(); + dayView.setChecked(dates != null && dates.contains(day)); + } + postInvalidate(); + } + + protected void updateUi() { + for (DayView dayView : dayViews) { + CalendarDay day = dayView.getDate(); + + if (day != null) + dayView.setupSelection(showOtherDates, day.isInRange(minDate, maxDate), isDayEnabled(day)); + } + postInvalidate(); + } + + protected void invalidateDecorators() { + final DayViewFacade facadeAccumulator = new DayViewFacade(); + for (DayView dayView : dayViews) { + facadeAccumulator.reset(); + for (DecoratorResult result : decoratorResults) { + if (result.decorator.shouldDecorate(dayView.getDate())) { + result.result.applyTo(facadeAccumulator); + } + } + dayView.applyFacade(facadeAccumulator); + } + } - private void buildWeekDays(LocalDate calendar) { - LocalDate local = calendar; - for (int i = 0; i < DEFAULT_DAYS_IN_WEEK; i++) { - WeekDayView weekDayView = new WeekDayView(getContext(), local.getDayOfWeek()); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { - weekDayView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); - } - weekDayViews.add(weekDayView); - addView(weekDayView); - local = local.plusDays(1); - } - } - - protected void addDayView(Collection dayViews, LocalDate temp) { - CalendarDay day = CalendarDay.from(temp); - DayView dayView = new DayView(getContext(), day); - dayView.setOnClickListener(this); - dayView.setOnLongClickListener(this); - dayViews.add(dayView); - addView(dayView, new LayoutParams()); - } - - protected LocalDate resetAndGetWorkingCalendar() { - final TemporalField firstDayOfWeek = WeekFields.of(this.firstDayOfWeek, 1).dayOfWeek(); - final LocalDate temp = getFirstViewDay().getDate().with(firstDayOfWeek, 1); - int dow = temp.getDayOfWeek().getValue(); - int delta = getFirstDayOfWeek().getValue() - dow; - //If the delta is positive, we want to remove a week - boolean removeRow = showOtherMonths(showOtherDates) ? delta >= 0 : delta > 0; - if (removeRow) { - delta -= DEFAULT_DAYS_IN_WEEK; - } - return temp.plusDays(delta); - } - - protected DayOfWeek getFirstDayOfWeek() { - return firstDayOfWeek; - } - - protected abstract void buildDayViews(Collection dayViews, LocalDate calendar); - - protected abstract boolean isDayEnabled(CalendarDay day); - - void setDayViewDecorators(List results) { - this.decoratorResults.clear(); - if (results != null) { - this.decoratorResults.addAll(results); - } - invalidateDecorators(); - } - - public void setWeekDayTextAppearance(int taId) { - for (WeekDayView weekDayView : weekDayViews) { - weekDayView.setTextAppearance(getContext(), taId); - } - } - - public void setDateTextAppearance(int taId) { - for (DayView dayView : dayViews) { - dayView.setTextAppearance(getContext(), taId); - } - } - - public void setShowOtherDates(@ShowOtherDates int showFlags) { - this.showOtherDates = showFlags; - updateUi(); - } - - public void setSelectionEnabled(boolean selectionEnabled) { - for (DayView dayView : dayViews) { - dayView.setOnClickListener(selectionEnabled ? this : null); - dayView.setClickable(selectionEnabled); - } - } - - public void setSelectionColor(int color) { - for (DayView dayView : dayViews) { - dayView.setSelectionColor(color); - } - } - - public void setWeekDayFormatter(WeekDayFormatter formatter) { - for (WeekDayView dayView : weekDayViews) { - dayView.setWeekDayFormatter(formatter); - } - } - - public void setDayFormatter(DayFormatter formatter) { - for (DayView dayView : dayViews) { - dayView.setDayFormatter(formatter); + @Override + public void onClick(final View v) { + if (v instanceof DayView) { + final DayView dayView = (DayView) v; + mcv.onDateClicked(dayView); + } } - } - - public void setDayFormatterContentDescription(DayFormatter formatter) { - for (DayView dayView : dayViews) { - dayView.setDayFormatterContentDescription(formatter); - } - } - - public void setMinimumDate(CalendarDay minDate) { - this.minDate = minDate; - updateUi(); - } - - public void setMaximumDate(CalendarDay maxDate) { - this.maxDate = maxDate; - updateUi(); - } - public void setSelectedDates(Collection dates) { - for (DayView dayView : dayViews) { - CalendarDay day = dayView.getDate(); - dayView.setChecked(dates != null && dates.contains(day)); + @Override + public boolean onLongClick(final View v) { + if (v instanceof DayView) { + final DayView dayView = (DayView) v; + mcv.onDateLongClicked(dayView); + return true; + } + return false; } - postInvalidate(); - } - protected void updateUi() { - for (DayView dayView : dayViews) { - CalendarDay day = dayView.getDate(); - dayView.setupSelection(showOtherDates, day.isInRange(minDate, maxDate), isDayEnabled(day)); + /* + * Custom ViewGroup Code + */ + + /** + * {@inheritDoc} + */ + @Override + protected LayoutParams generateDefaultLayoutParams() { + return new LayoutParams(); + } + + /** + * {@inheritDoc} + */ + @Override + protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { + final int specWidthSize = MeasureSpec.getSize(widthMeasureSpec); + final int specWidthMode = MeasureSpec.getMode(widthMeasureSpec); + final int specHeightSize = MeasureSpec.getSize(heightMeasureSpec); + final int specHeightMode = MeasureSpec.getMode(heightMeasureSpec); + + //We expect to be somewhere inside a MaterialCalendarView, which should measure EXACTLY + if (specHeightMode == MeasureSpec.UNSPECIFIED || specWidthMode == MeasureSpec.UNSPECIFIED) { + throw new IllegalStateException("CalendarPagerView should never be left to decide it's size"); + } + + //The spec width should be a correct multiple + final int measureTileWidth = specWidthSize / DEFAULT_DAYS_IN_WEEK; + final int measureTileHeight = specHeightSize / getRows(); + + //Just use the spec sizes + setMeasuredDimension(specWidthSize, specHeightSize); + + int count = getChildCount(); + + for (int i = 0; i < count; i++) { + final View child = getChildAt(i); + + int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec( + measureTileWidth, + MeasureSpec.EXACTLY + ); + + int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( + measureTileHeight, + MeasureSpec.EXACTLY + ); + + child.measure(childWidthMeasureSpec, childHeightMeasureSpec); + } } - postInvalidate(); - } - protected void invalidateDecorators() { - final DayViewFacade facadeAccumulator = new DayViewFacade(); - for (DayView dayView : dayViews) { - facadeAccumulator.reset(); - for (DecoratorResult result : decoratorResults) { - if (result.decorator.shouldDecorate(dayView.getDate())) { - result.result.applyTo(facadeAccumulator); + /** + * Return the number of rows to display per page + */ + protected abstract int getRows(); + + /** + * {@inheritDoc} + */ + @Override + protected void onLayout(boolean changed, int left, int top, int right, int bottom) { + final int parentWidth = getWidth(); + final int count = getChildCount(); + final int parentLeft = 0; + final int parentRight = parentWidth; + + int childTop = 0; + int childLeft = parentLeft; + int childRight = parentRight; + + for (int i = 0; i < count; i++) { + final View child = getChildAt(i); + + final int width = child.getMeasuredWidth(); + final int height = child.getMeasuredHeight(); + + if (LocalUtils.isRTL()) { + child.layout(childRight - width, childTop, childRight, childTop + height); + childRight -= width; + } else { + child.layout(childLeft, childTop, childLeft + width, childTop + height); + childLeft += width; + } + + //We should warp every so many children + if (i % DEFAULT_DAYS_IN_WEEK == (DEFAULT_DAYS_IN_WEEK - 1)) { + childLeft = parentLeft; + childRight = parentRight; + childTop += height; + } } - } - dayView.applyFacade(facadeAccumulator); - } - } - - @Override - public void onClick(final View v) { - if (v instanceof DayView) { - final DayView dayView = (DayView) v; - mcv.onDateClicked(dayView); - } - } - - @Override - public boolean onLongClick(final View v) { - if (v instanceof DayView) { - final DayView dayView = (DayView) v; - mcv.onDateLongClicked(dayView); - return true; - } - return false; - } - - /* - * Custom ViewGroup Code - */ - - /** - * {@inheritDoc} - */ - @Override - protected LayoutParams generateDefaultLayoutParams() { - return new LayoutParams(); - } - - /** - * {@inheritDoc} - */ - @Override - protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { - final int specWidthSize = MeasureSpec.getSize(widthMeasureSpec); - final int specWidthMode = MeasureSpec.getMode(widthMeasureSpec); - final int specHeightSize = MeasureSpec.getSize(heightMeasureSpec); - final int specHeightMode = MeasureSpec.getMode(heightMeasureSpec); - - //We expect to be somewhere inside a MaterialCalendarView, which should measure EXACTLY - if (specHeightMode == MeasureSpec.UNSPECIFIED || specWidthMode == MeasureSpec.UNSPECIFIED) { - throw new IllegalStateException("CalendarPagerView should never be left to decide it's size"); - } - - //The spec width should be a correct multiple - final int measureTileWidth = specWidthSize / DEFAULT_DAYS_IN_WEEK; - final int measureTileHeight = specHeightSize / getRows(); - - //Just use the spec sizes - setMeasuredDimension(specWidthSize, specHeightSize); - - int count = getChildCount(); - - for (int i = 0; i < count; i++) { - final View child = getChildAt(i); - - int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec( - measureTileWidth, - MeasureSpec.EXACTLY - ); - - int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( - measureTileHeight, - MeasureSpec.EXACTLY - ); - - child.measure(childWidthMeasureSpec, childHeightMeasureSpec); - } - } - - /** - * Return the number of rows to display per page - */ - protected abstract int getRows(); - - /** - * {@inheritDoc} - */ - @Override - protected void onLayout(boolean changed, int left, int top, int right, int bottom) { - final int parentWidth = getWidth(); - final int count = getChildCount(); - final int parentLeft = 0; - final int parentRight = parentWidth; - - int childTop = 0; - int childLeft = parentLeft; - int childRight = parentRight; - - for (int i = 0; i < count; i++) { - final View child = getChildAt(i); - - final int width = child.getMeasuredWidth(); - final int height = child.getMeasuredHeight(); - - if (LocalUtils.isRTL()) { - child.layout(childRight - width, childTop, childRight, childTop + height); - childRight -= width; - } else { - child.layout(childLeft, childTop, childLeft + width, childTop + height); - childLeft += width; - } - - //We should warp every so many children - if (i % DEFAULT_DAYS_IN_WEEK == (DEFAULT_DAYS_IN_WEEK - 1)) { - childLeft = parentLeft; - childRight = parentRight; - childTop += height; - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public LayoutParams generateLayoutParams(AttributeSet attrs) { - return new LayoutParams(); - } - - @Override - public boolean shouldDelayChildPressedState() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { - return p instanceof LayoutParams; - } - - @Override - protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { - return new LayoutParams(); - } - - @Override - public void onInitializeAccessibilityEvent(@NonNull AccessibilityEvent event) { - super.onInitializeAccessibilityEvent(event); - event.setClassName(CalendarPagerView.class.getName()); - } - - @Override - public void onInitializeAccessibilityNodeInfo(@NonNull AccessibilityNodeInfo info) { - super.onInitializeAccessibilityNodeInfo(info); - info.setClassName(CalendarPagerView.class.getName()); - } - - protected CalendarDay getFirstViewDay() { - return firstViewDay; - } - - /** - * Simple layout params class for MonthView, since every child is the same size - */ - protected static class LayoutParams extends MarginLayoutParams { + } /** * {@inheritDoc} */ - public LayoutParams() { - super(WRAP_CONTENT, WRAP_CONTENT); + @Override + public LayoutParams generateLayoutParams(AttributeSet attrs) { + return new LayoutParams(); + } + + @Override + public boolean shouldDelayChildPressedState() { + return false; + } + + /** + * {@inheritDoc} + */ + @Override + protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { + return p instanceof LayoutParams; + } + + @Override + protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { + return new LayoutParams(); + } + + @Override + public void onInitializeAccessibilityEvent(@NonNull AccessibilityEvent event) { + super.onInitializeAccessibilityEvent(event); + event.setClassName(CalendarPagerView.class.getName()); + } + + @Override + public void onInitializeAccessibilityNodeInfo(@NonNull AccessibilityNodeInfo info) { + super.onInitializeAccessibilityNodeInfo(info); + info.setClassName(CalendarPagerView.class.getName()); + } + + protected CalendarDay getFirstViewDay() { + return firstViewDay; + } + + /** + * Simple layout params class for MonthView, since every child is the same size + */ + protected static class LayoutParams extends MarginLayoutParams { + + /** + * {@inheritDoc} + */ + public LayoutParams() { + super(WRAP_CONTENT, WRAP_CONTENT); + } } - } } diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/DateRangeIndex.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/DateRangeIndex.java deleted file mode 100644 index ff1c3811..00000000 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/DateRangeIndex.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.prolificinteractive.materialcalendarview; - -/** - * Use math to calculate first days of months or weeks by position from a minimum date (and first - * day of week in case of weekly range). - */ -interface DateRangeIndex { - - /** - * Count of pages displayed between 2 dates. - */ - int getCount(); - - /** - * Index of the page where the date is displayed. - */ - int indexOf(CalendarDay day); - - /** - * Get the first date at the position within the index. - */ - CalendarDay getItem(int position); -} diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/DayView.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/DayView.java index 675e5f94..47cf74d4 100644 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/DayView.java +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/DayView.java @@ -19,8 +19,10 @@ import android.text.Spanned; import android.view.Gravity; import android.view.View; + import com.prolificinteractive.materialcalendarview.MaterialCalendarView.ShowOtherDates; import com.prolificinteractive.materialcalendarview.format.DayFormatter; + import java.util.List; import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.showDecoratedDisabled; @@ -30,276 +32,280 @@ /** * Display one day of a {@linkplain MaterialCalendarView} */ -@SuppressLint("ViewConstructor") class DayView extends AppCompatCheckedTextView { +@SuppressLint("ViewConstructor") +class DayView extends AppCompatCheckedTextView { - private CalendarDay date; - private int selectionColor = Color.GRAY; + private CalendarDay date; + private int selectionColor = Color.GRAY; - private final int fadeTime; - private Drawable customBackground = null; - private Drawable selectionDrawable; - private Drawable mCircleDrawable; - private DayFormatter formatter = DayFormatter.DEFAULT; - private DayFormatter contentDescriptionFormatter = formatter; + private final int fadeTime; + private Drawable customBackground = null; + private Drawable selectionDrawable; + private Drawable mCircleDrawable; + private DayFormatter formatter = DayFormatter.DEFAULT; + private DayFormatter contentDescriptionFormatter = formatter; - private boolean isInRange = true; - private boolean isInMonth = true; - private boolean isDecoratedDisabled = false; - @ShowOtherDates - private int showOtherDates = MaterialCalendarView.SHOW_DEFAULTS; + private boolean isInRange = true; + private boolean isInMonth = true; + private boolean isDecoratedDisabled = false; + @ShowOtherDates + private int showOtherDates = MaterialCalendarView.SHOW_DEFAULTS; - public DayView(Context context, CalendarDay day) { - super(context); + public DayView(Context context, CalendarDay day) { + super(context); - fadeTime = getResources().getInteger(android.R.integer.config_shortAnimTime); + fadeTime = getResources().getInteger(android.R.integer.config_shortAnimTime); - setSelectionColor(this.selectionColor); + setSelectionColor(this.selectionColor); - setGravity(Gravity.CENTER); + setGravity(Gravity.CENTER); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { - setTextAlignment(TEXT_ALIGNMENT_CENTER); - } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { + setTextAlignment(TEXT_ALIGNMENT_CENTER); + } - setDay(day); - } - - public void setDay(CalendarDay date) { - this.date = date; - setText(getLabel()); - } - - /** - * Set the new label formatter and reformat the current label. This preserves current spans. - * - * @param formatter new label formatter - */ - public void setDayFormatter(DayFormatter formatter) { - this.contentDescriptionFormatter = contentDescriptionFormatter == this.formatter ? - formatter : contentDescriptionFormatter; - this.formatter = formatter == null ? DayFormatter.DEFAULT : formatter; - CharSequence currentLabel = getText(); - Object[] spans = null; - if (currentLabel instanceof Spanned) { - spans = ((Spanned) currentLabel).getSpans(0, currentLabel.length(), Object.class); + setDay(day); } - SpannableString newLabel = new SpannableString(getLabel()); - if (spans != null) { - for (Object span : spans) { - newLabel.setSpan(span, 0, newLabel.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); - } + + public void setDay(CalendarDay date) { + this.date = date; + setText(getLabel()); } - setText(newLabel); - } - - /** - * Set the new content description formatter and reformat the current content description. - * - * @param formatter new content description formatter - */ - public void setDayFormatterContentDescription(DayFormatter formatter) { - this.contentDescriptionFormatter = formatter == null ? this.formatter : formatter; - setContentDescription(getContentDescriptionLabel()); - } - - @NonNull - public String getLabel() { - return formatter.format(date); - } - - @NonNull - public String getContentDescriptionLabel() { - return contentDescriptionFormatter == null ? formatter.format(date) - : contentDescriptionFormatter.format(date); - } - - public void setSelectionColor(int color) { - this.selectionColor = color; - regenerateBackground(); - } - - /** - * @param drawable custom selection drawable - */ - public void setSelectionDrawable(Drawable drawable) { - if (drawable == null) { - this.selectionDrawable = null; - } else { - this.selectionDrawable = drawable.getConstantState().newDrawable(getResources()); + + /** + * Set the new label formatter and reformat the current label. This preserves current spans. + * + * @param formatter new label formatter + */ + public void setDayFormatter(DayFormatter formatter) { + this.contentDescriptionFormatter = contentDescriptionFormatter == this.formatter ? + formatter : contentDescriptionFormatter; + this.formatter = formatter == null ? DayFormatter.DEFAULT : formatter; + CharSequence currentLabel = getText(); + Object[] spans = null; + if (currentLabel instanceof Spanned) { + spans = ((Spanned) currentLabel).getSpans(0, currentLabel.length(), Object.class); + } + SpannableString newLabel = new SpannableString(getLabel()); + if (spans != null) { + for (Object span : spans) { + newLabel.setSpan(span, 0, newLabel.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + } + } + setText(newLabel); } - regenerateBackground(); - } - - /** - * @param drawable background to draw behind everything else - */ - public void setCustomBackground(Drawable drawable) { - if (drawable == null) { - this.customBackground = null; - } else { - this.customBackground = drawable.getConstantState().newDrawable(getResources()); + + /** + * Set the new content description formatter and reformat the current content description. + * + * @param formatter new content description formatter + */ + public void setDayFormatterContentDescription(DayFormatter formatter) { + this.contentDescriptionFormatter = formatter == null ? this.formatter : formatter; + setContentDescription(getContentDescriptionLabel()); } - invalidate(); - } - public CalendarDay getDate() { - return date; - } + @NonNull + public String getLabel() { + if (date != null) + return formatter.format(date); - private void setEnabled() { - boolean enabled = isInMonth && isInRange && !isDecoratedDisabled; - super.setEnabled(isInRange && !isDecoratedDisabled); + return "0"; + } - boolean showOtherMonths = showOtherMonths(showOtherDates); - boolean showOutOfRange = showOutOfRange(showOtherDates) || showOtherMonths; - boolean showDecoratedDisabled = showDecoratedDisabled(showOtherDates); + @NonNull + public String getContentDescriptionLabel() { + return contentDescriptionFormatter == null ? formatter.format(date) + : contentDescriptionFormatter.format(date); + } - boolean shouldBeVisible = enabled; + public void setSelectionColor(int color) { + this.selectionColor = color; + regenerateBackground(); + } - if (!isInMonth && showOtherMonths) { - shouldBeVisible = true; + /** + * @param drawable custom selection drawable + */ + public void setSelectionDrawable(Drawable drawable) { + if (drawable == null) { + this.selectionDrawable = null; + } else { + this.selectionDrawable = drawable.getConstantState().newDrawable(getResources()); + } + regenerateBackground(); } - if (!isInRange && showOutOfRange) { - shouldBeVisible |= isInMonth; + /** + * @param drawable background to draw behind everything else + */ + public void setCustomBackground(Drawable drawable) { + if (drawable == null) { + this.customBackground = null; + } else { + this.customBackground = drawable.getConstantState().newDrawable(getResources()); + } + invalidate(); } - if (isDecoratedDisabled && showDecoratedDisabled) { - shouldBeVisible |= isInMonth && isInRange; + public CalendarDay getDate() { + return date; } - if (!isInMonth && shouldBeVisible) { - setTextColor(getTextColors().getColorForState( - new int[] { -android.R.attr.state_enabled }, Color.GRAY)); + private void setEnabled() { + boolean enabled = isInMonth && isInRange && !isDecoratedDisabled; + super.setEnabled(isInRange && !isDecoratedDisabled); + + boolean showOtherMonths = showOtherMonths(showOtherDates); + boolean showOutOfRange = showOutOfRange(showOtherDates) || showOtherMonths; + boolean showDecoratedDisabled = showDecoratedDisabled(showOtherDates); + + boolean shouldBeVisible = enabled; + + if (!isInMonth && showOtherMonths) { + shouldBeVisible = true; + } + + if (!isInRange && showOutOfRange) { + shouldBeVisible |= isInMonth; + } + + if (isDecoratedDisabled && showDecoratedDisabled) { + shouldBeVisible |= isInMonth && isInRange; + } + + if (!isInMonth && shouldBeVisible) { + setTextColor(getTextColors().getColorForState( + new int[]{-android.R.attr.state_enabled}, Color.GRAY)); + } + setVisibility(shouldBeVisible ? View.VISIBLE : View.INVISIBLE); } - setVisibility(shouldBeVisible ? View.VISIBLE : View.INVISIBLE); - } - - protected void setupSelection( - @ShowOtherDates int showOtherDates, - boolean inRange, - boolean inMonth) { - this.showOtherDates = showOtherDates; - this.isInMonth = inMonth; - this.isInRange = inRange; - setEnabled(); - } - - private final Rect tempRect = new Rect(); - private final Rect circleDrawableRect = new Rect(); - - @Override - protected void onDraw(@NonNull Canvas canvas) { - if (customBackground != null) { - customBackground.setBounds(tempRect); - customBackground.setState(getDrawableState()); - customBackground.draw(canvas); + + protected void setupSelection( + @ShowOtherDates int showOtherDates, + boolean inRange, + boolean inMonth) { + this.showOtherDates = showOtherDates; + this.isInMonth = inMonth; + this.isInRange = inRange; + setEnabled(); } - mCircleDrawable.setBounds(circleDrawableRect); + private final Rect tempRect = new Rect(); + private final Rect circleDrawableRect = new Rect(); + + @Override + protected void onDraw(@NonNull Canvas canvas) { + if (customBackground != null) { + customBackground.setBounds(tempRect); + customBackground.setState(getDrawableState()); + customBackground.draw(canvas); + } - super.onDraw(canvas); - } + mCircleDrawable.setBounds(circleDrawableRect); - private void regenerateBackground() { - if (selectionDrawable != null) { - setBackgroundDrawable(selectionDrawable); - } else { - mCircleDrawable = generateBackground(selectionColor, fadeTime, circleDrawableRect); - setBackgroundDrawable(mCircleDrawable); + super.onDraw(canvas); } - } - - private static Drawable generateBackground(int color, int fadeTime, Rect bounds) { - StateListDrawable drawable = new StateListDrawable(); - drawable.setExitFadeDuration(fadeTime); - drawable.addState(new int[] { android.R.attr.state_checked }, generateCircleDrawable(color)); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - drawable.addState( - new int[] { android.R.attr.state_pressed }, - generateRippleDrawable(color, bounds) - ); - } else { - drawable.addState(new int[] { android.R.attr.state_pressed }, generateCircleDrawable(color)); + + private void regenerateBackground() { + if (selectionDrawable != null) { + setBackgroundDrawable(selectionDrawable); + } else { + mCircleDrawable = generateBackground(selectionColor, fadeTime, circleDrawableRect); + setBackgroundDrawable(mCircleDrawable); + } } - drawable.addState(new int[] { }, generateCircleDrawable(Color.TRANSPARENT)); - - return drawable; - } - - private static Drawable generateCircleDrawable(final int color) { - ShapeDrawable drawable = new ShapeDrawable(new OvalShape()); - drawable.getPaint().setColor(color); - return drawable; - } - - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - private static Drawable generateRippleDrawable(final int color, Rect bounds) { - ColorStateList list = ColorStateList.valueOf(color); - Drawable mask = generateCircleDrawable(Color.WHITE); - RippleDrawable rippleDrawable = new RippleDrawable(list, null, mask); - // API 21 - if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) { - rippleDrawable.setBounds(bounds); + private static Drawable generateBackground(int color, int fadeTime, Rect bounds) { + StateListDrawable drawable = new StateListDrawable(); + drawable.setExitFadeDuration(fadeTime); + drawable.addState(new int[]{android.R.attr.state_checked}, generateCircleDrawable(color)); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + drawable.addState( + new int[]{android.R.attr.state_pressed}, + generateRippleDrawable(color, bounds) + ); + } else { + drawable.addState(new int[]{android.R.attr.state_pressed}, generateCircleDrawable(color)); + } + + drawable.addState(new int[]{}, generateCircleDrawable(Color.TRANSPARENT)); + + return drawable; } - // API 22. Technically harmless to leave on for API 21 and 23, but not worth risking for 23+ - if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1) { - int center = (bounds.left + bounds.right) / 2; - rippleDrawable.setHotspotBounds(center, bounds.top, center, bounds.bottom); + private static Drawable generateCircleDrawable(final int color) { + ShapeDrawable drawable = new ShapeDrawable(new OvalShape()); + drawable.getPaint().setColor(color); + return drawable; } - return rippleDrawable; - } - - /** - * @param facade apply the facade to us - */ - void applyFacade(DayViewFacade facade) { - this.isDecoratedDisabled = facade.areDaysDisabled(); - setEnabled(); - - setCustomBackground(facade.getBackgroundDrawable()); - setSelectionDrawable(facade.getSelectionDrawable()); - - // Facade has spans - List spans = facade.getSpans(); - if (!spans.isEmpty()) { - String label = getLabel(); - SpannableString formattedLabel = new SpannableString(getLabel()); - for (DayViewFacade.Span span : spans) { - formattedLabel.setSpan(span.span, 0, label.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); - } - setText(formattedLabel); + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + private static Drawable generateRippleDrawable(final int color, Rect bounds) { + ColorStateList list = ColorStateList.valueOf(color); + Drawable mask = generateCircleDrawable(Color.WHITE); + RippleDrawable rippleDrawable = new RippleDrawable(list, null, mask); + // API 21 + if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) { + rippleDrawable.setBounds(bounds); + } + + // API 22. Technically harmless to leave on for API 21 and 23, but not worth risking for 23+ + if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1) { + int center = (bounds.left + bounds.right) / 2; + rippleDrawable.setHotspotBounds(center, bounds.top, center, bounds.bottom); + } + + return rippleDrawable; } - // Reset in case it was customized previously - else { - setText(getLabel()); + + /** + * @param facade apply the facade to us + */ + void applyFacade(DayViewFacade facade) { + this.isDecoratedDisabled = facade.areDaysDisabled(); + setEnabled(); + + setCustomBackground(facade.getBackgroundDrawable()); + setSelectionDrawable(facade.getSelectionDrawable()); + + // Facade has spans + List spans = facade.getSpans(); + if (!spans.isEmpty()) { + String label = getLabel(); + SpannableString formattedLabel = new SpannableString(getLabel()); + for (DayViewFacade.Span span : spans) { + formattedLabel.setSpan(span.getSpan(), 0, label.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + } + setText(formattedLabel); + } + // Reset in case it was customized previously + else { + setText(getLabel()); + } } - } - - @Override - protected void onLayout(boolean changed, int left, int top, int right, int bottom) { - super.onLayout(changed, left, top, right, bottom); - calculateBounds(right - left, bottom - top); - regenerateBackground(); - } - - private void calculateBounds(int width, int height) { - final int radius = Math.min(height, width); - final int offset = Math.abs(height - width) / 2; - - // Lollipop platform bug. Circle drawable offset needs to be half of normal offset - final int circleOffset = - Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP ? offset / 2 : offset; - - if (width >= height) { - tempRect.set(offset, 0, radius + offset, height); - circleDrawableRect.set(circleOffset, 0, radius + circleOffset, height); - } else { - tempRect.set(0, offset, width, radius + offset); - circleDrawableRect.set(0, circleOffset, width, radius + circleOffset); + + @Override + protected void onLayout(boolean changed, int left, int top, int right, int bottom) { + super.onLayout(changed, left, top, right, bottom); + calculateBounds(right - left, bottom - top); + regenerateBackground(); + } + + private void calculateBounds(int width, int height) { + final int radius = Math.min(height, width); + final int offset = Math.abs(height - width) / 2; + + // Lollipop platform bug. Circle drawable offset needs to be half of normal offset + final int circleOffset = + Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP ? offset / 2 : offset; + + if (width >= height) { + tempRect.set(offset, 0, radius + offset, height); + circleDrawableRect.set(circleOffset, 0, radius + circleOffset, height); + } else { + tempRect.set(0, offset, width, radius + offset); + circleDrawableRect.set(0, circleOffset, width, radius + circleOffset); + } } - } } diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/DayViewDecorator.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/DayViewDecorator.java deleted file mode 100644 index 4b7585c1..00000000 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/DayViewDecorator.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.prolificinteractive.materialcalendarview; - -/** - * Decorate Day views with drawables and text manipulation - */ -public interface DayViewDecorator { - - /** - * Determine if a specific day should be decorated - * - * @param day {@linkplain CalendarDay} to possibly decorate - * @return true if this decorator should be applied to the provided day - */ - boolean shouldDecorate(CalendarDay day); - - /** - * Set decoration options onto a facade to be applied to all relevant days - * - * @param view View to decorate - */ - void decorate(DayViewFacade view); -} diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/DayViewFacade.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/DayViewFacade.java deleted file mode 100644 index cbffdfec..00000000 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/DayViewFacade.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.prolificinteractive.materialcalendarview; - -import android.graphics.drawable.Drawable; -import android.support.annotation.NonNull; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -/** - * Abstraction layer to help in decorating Day views - */ -public class DayViewFacade { - - private boolean isDecorated; - - private Drawable backgroundDrawable = null; - private Drawable selectionDrawable = null; - private final LinkedList spans = new LinkedList<>(); - private boolean daysDisabled = false; - - DayViewFacade() { - isDecorated = false; - } - - /** - * Set a drawable to draw behind everything else - * - * @param drawable Drawable to draw behind everything - */ - public void setBackgroundDrawable(@NonNull Drawable drawable) { - if (drawable == null) { - throw new IllegalArgumentException("Cannot be null"); - } - this.backgroundDrawable = drawable; - isDecorated = true; - } - - /** - * Set a custom selection drawable - * TODO: define states that can/should be used in StateListDrawables - * - * @param drawable the drawable for selection - */ - public void setSelectionDrawable(@NonNull Drawable drawable) { - if (drawable == null) { - throw new IllegalArgumentException("Cannot be null"); - } - selectionDrawable = drawable; - isDecorated = true; - } - - /** - * Add a span to the entire text of a day - * - * @param span text span instance - */ - public void addSpan(@NonNull Object span) { - if (spans != null) { - this.spans.add(new Span(span)); - isDecorated = true; - } - } - - /** - *

Set days to be in a disabled state, or re-enabled.

- *

Note, passing true here will not override minimum and maximum dates, if set. - * This will only re-enable disabled dates.

- * - * @param daysDisabled true to disable days, false to re-enable days - */ - public void setDaysDisabled(boolean daysDisabled) { - this.daysDisabled = daysDisabled; - this.isDecorated = true; - } - - void reset() { - backgroundDrawable = null; - selectionDrawable = null; - spans.clear(); - isDecorated = false; - daysDisabled = false; - } - - /** - * Apply things set this to other - * - * @param other facade to apply our data to - */ - void applyTo(DayViewFacade other) { - if (selectionDrawable != null) { - other.setSelectionDrawable(selectionDrawable); - } - if (backgroundDrawable != null) { - other.setBackgroundDrawable(backgroundDrawable); - } - other.spans.addAll(spans); - other.isDecorated |= this.isDecorated; - other.daysDisabled = daysDisabled; - } - - boolean isDecorated() { - return isDecorated; - } - - Drawable getSelectionDrawable() { - return selectionDrawable; - } - - Drawable getBackgroundDrawable() { - return backgroundDrawable; - } - - List getSpans() { - return Collections.unmodifiableList(spans); - } - - /** - * Are days from this facade disabled - * - * @return true if disabled, false if not re-enabled - */ - public boolean areDaysDisabled() { - return daysDisabled; - } - - static class Span { - - final Object span; - - public Span(Object span) { - this.span = span; - } - } -} diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/DayViewFacade.kt b/library/src/main/java/com/prolificinteractive/materialcalendarview/DayViewFacade.kt new file mode 100644 index 00000000..4776ef87 --- /dev/null +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/DayViewFacade.kt @@ -0,0 +1,90 @@ +package com.prolificinteractive.materialcalendarview + +import android.graphics.drawable.Drawable +import java.util.* + +/** + * Abstraction layer to help in decorating Day views + */ +class DayViewFacade { + + val isDecorated: Boolean + get() = selectionDrawable != null || backgroundDrawable != null || spans.size > 0 || daysDisabled + + /** TODO + * use a default value since setter does not allow null + * */ + + /** + * Set a drawable to draw behind everything else + * + * Drawable to draw behind everything + */ + var backgroundDrawable: Drawable? = null + + /** TODO + * use a default value since setter does not allow null + * */ + /** + * Set a custom selection drawable + * TODO: define states that can/should be used in StateListDrawables + * + */ + var selectionDrawable: Drawable? = null + + + val spans = LinkedList() + + var daysDisabled = false + + + /** + * Add a span to the entire text of a day + * + * @param span text span instance + */ + + fun addSpan(span: Any?) { + span?.let { + spans.add(Span(span)) + } + } + + fun reset() { + backgroundDrawable = null + selectionDrawable = null + spans.clear() + daysDisabled = false + } + + /** + * Apply things set this to other + * + * @param other facade to apply our data to + */ + fun applyTo(other: DayViewFacade) { + + selectionDrawable?.let { + other.selectionDrawable = it + } + + backgroundDrawable?.let { + other.selectionDrawable = it + } + + other.spans.addAll(spans) + other.daysDisabled = daysDisabled + + } + + /** + * Are days from this facade disabled + * + * @return true if disabled, false if not re-enabled + */ + fun areDaysDisabled(): Boolean { + return daysDisabled + } + + class Span(val span: Any) +} \ No newline at end of file diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/DecoratorResult.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/DecoratorResult.java index 392897f3..e84339a8 100644 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/DecoratorResult.java +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/DecoratorResult.java @@ -1,5 +1,7 @@ package com.prolificinteractive.materialcalendarview; +import com.prolificinteractive.materialcalendarview.listeners.DayViewDecorator; + class DecoratorResult { public final DayViewDecorator decorator; public final DayViewFacade result; diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java index 623b4a69..6fca17ad 100644 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java @@ -27,11 +27,19 @@ import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; + +import com.jakewharton.threetenabp.AndroidThreeTen; import com.prolificinteractive.materialcalendarview.format.ArrayWeekDayFormatter; import com.prolificinteractive.materialcalendarview.format.DayFormatter; import com.prolificinteractive.materialcalendarview.format.MonthArrayTitleFormatter; import com.prolificinteractive.materialcalendarview.format.TitleFormatter; import com.prolificinteractive.materialcalendarview.format.WeekDayFormatter; +import com.prolificinteractive.materialcalendarview.listeners.DayViewDecorator; +import com.prolificinteractive.materialcalendarview.listeners.OnDateLongClickListener; +import com.prolificinteractive.materialcalendarview.listeners.OnDateSelectedListener; +import com.prolificinteractive.materialcalendarview.listeners.OnMonthChangedListener; +import com.prolificinteractive.materialcalendarview.listeners.OnRangeSelectedListener; + import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; @@ -40,6 +48,7 @@ import java.util.Collection; import java.util.List; import java.util.Locale; + import org.threeten.bp.DayOfWeek; import org.threeten.bp.LocalDate; import org.threeten.bp.temporal.WeekFields; @@ -68,1951 +77,1955 @@ */ public class MaterialCalendarView extends ViewGroup { - public static final int INVALID_TILE_DIMENSION = -10; - - /** - * {@linkplain IntDef} annotation for selection mode. - * - * @see #setSelectionMode(int) - * @see #getSelectionMode() - */ - @Retention(RetentionPolicy.SOURCE) - @IntDef( - { SELECTION_MODE_NONE, SELECTION_MODE_SINGLE, SELECTION_MODE_MULTIPLE, SELECTION_MODE_RANGE }) - public @interface SelectionMode { - } - - /** - * Selection mode that disallows all selection. - * When changing to this mode, current selection will be cleared. - */ - public static final int SELECTION_MODE_NONE = 0; - - /** - * Selection mode that allows one selected date at one time. This is the default mode. - * When switching from {@linkplain #SELECTION_MODE_MULTIPLE}, this will select the same date - * as from {@linkplain #getSelectedDate()}, which should be the last selected date - */ - public static final int SELECTION_MODE_SINGLE = 1; - - /** - * Selection mode which allows more than one selected date at one time. - */ - public static final int SELECTION_MODE_MULTIPLE = 2; - - /** - * Selection mode which allows selection of a range between two dates - */ - public static final int SELECTION_MODE_RANGE = 3; - - /** - * {@linkplain IntDef} annotation for showOtherDates. - * - * @see #setShowOtherDates(int) - * @see #getShowOtherDates() - */ - @SuppressLint("UniqueConstants") - @Retention(RetentionPolicy.SOURCE) - @IntDef(flag = true, value = { - SHOW_NONE, SHOW_ALL, SHOW_DEFAULTS, - SHOW_OUT_OF_RANGE, SHOW_OTHER_MONTHS, SHOW_DECORATED_DISABLED - }) - public @interface ShowOtherDates { - } - - /** - * Do not show any non-enabled dates - */ - public static final int SHOW_NONE = 0; - - /** - * Show dates from the proceeding and successive months, in a disabled state. - * This flag also enables the {@link #SHOW_OUT_OF_RANGE} flag to prevent odd blank areas. - */ - public static final int SHOW_OTHER_MONTHS = 1; - - /** - * Show dates that are outside of the min-max range. - * This will only show days from the current month unless {@link #SHOW_OTHER_MONTHS} is enabled. - */ - public static final int SHOW_OUT_OF_RANGE = 1 << 1; - - /** - * Show days that are individually disabled with decorators. - * This will only show dates in the current month and inside the minimum and maximum date range. - */ - public static final int SHOW_DECORATED_DISABLED = 1 << 2; - - /** - * The default flags for showing non-enabled dates. Currently only shows {@link - * #SHOW_DECORATED_DISABLED} - */ - public static final int SHOW_DEFAULTS = SHOW_DECORATED_DISABLED; - - /** - * Show all the days - */ - public static final int SHOW_ALL = - SHOW_OTHER_MONTHS | SHOW_OUT_OF_RANGE | SHOW_DECORATED_DISABLED; - - /** - * Use this orientation to animate the title vertically - */ - public static final int VERTICAL = 0; - - /** - * Use this orientation to animate the title horizontally - */ - public static final int HORIZONTAL = 1; - - /** - * Default tile size in DIPs. This is used in cases where there is no tile size specificed and the - * view is set to {@linkplain ViewGroup.LayoutParams#WRAP_CONTENT WRAP_CONTENT} - */ - public static final int DEFAULT_TILE_SIZE_DP = 44; - private static final int DEFAULT_DAYS_IN_WEEK = 7; - private static final int DEFAULT_MAX_WEEKS = 6; - private static final int DAY_NAMES_ROW = 1; - - private final TitleChanger titleChanger; - - private final TextView title; - private final ImageView buttonPast; - private final ImageView buttonFuture; - private final CalendarPager pager; - private CalendarPagerAdapter adapter; - private CalendarDay currentMonth; - private LinearLayout topbar; - private CalendarMode calendarMode; - /** - * Used for the dynamic calendar height. - */ - private boolean mDynamicHeightEnabled; - - private final ArrayList dayViewDecorators = new ArrayList<>(); - - private final OnClickListener onClickListener = new OnClickListener() { - @Override - public void onClick(View v) { - if (v == buttonFuture) { - pager.setCurrentItem(pager.getCurrentItem() + 1, true); - } else if (v == buttonPast) { - pager.setCurrentItem(pager.getCurrentItem() - 1, true); - } + public static final int INVALID_TILE_DIMENSION = -10; + + /** + * {@linkplain IntDef} annotation for selection mode. + * + * @see #setSelectionMode(int) + * @see #getSelectionMode() + */ + @Retention(RetentionPolicy.SOURCE) + @IntDef( + {SELECTION_MODE_NONE, SELECTION_MODE_SINGLE, SELECTION_MODE_MULTIPLE, SELECTION_MODE_RANGE}) + public @interface SelectionMode { + } + + /** + * Selection mode that disallows all selection. + * When changing to this mode, current selection will be cleared. + */ + public static final int SELECTION_MODE_NONE = 0; + + /** + * Selection mode that allows one selected date at one time. This is the default mode. + * When switching from {@linkplain #SELECTION_MODE_MULTIPLE}, this will select the same date + * as from {@linkplain #getSelectedDate()}, which should be the last selected date + */ + public static final int SELECTION_MODE_SINGLE = 1; + + /** + * Selection mode which allows more than one selected date at one time. + */ + public static final int SELECTION_MODE_MULTIPLE = 2; + + /** + * Selection mode which allows selection of a range between two dates + */ + public static final int SELECTION_MODE_RANGE = 3; + + /** + * {@linkplain IntDef} annotation for showOtherDates. + * + * @see #setShowOtherDates(int) + * @see #getShowOtherDates() + */ + @SuppressLint("UniqueConstants") + @Retention(RetentionPolicy.SOURCE) + @IntDef(flag = true, value = { + SHOW_NONE, SHOW_ALL, SHOW_DEFAULTS, + SHOW_OUT_OF_RANGE, SHOW_OTHER_MONTHS, SHOW_DECORATED_DISABLED + }) + public @interface ShowOtherDates { } - }; - private final ViewPager.OnPageChangeListener pageChangeListener = - new ViewPager.OnPageChangeListener() { + /** + * Do not show any non-enabled dates + */ + public static final int SHOW_NONE = 0; + + /** + * Show dates from the proceeding and successive months, in a disabled state. + * This flag also enables the {@link #SHOW_OUT_OF_RANGE} flag to prevent odd blank areas. + */ + public static final int SHOW_OTHER_MONTHS = 1; + + /** + * Show dates that are outside of the min-max range. + * This will only show days from the current month unless {@link #SHOW_OTHER_MONTHS} is enabled. + */ + public static final int SHOW_OUT_OF_RANGE = 1 << 1; + + /** + * Show days that are individually disabled with decorators. + * This will only show dates in the current month and inside the minimum and maximum date range. + */ + public static final int SHOW_DECORATED_DISABLED = 1 << 2; + + /** + * The default flags for showing non-enabled dates. Currently only shows {@link + * #SHOW_DECORATED_DISABLED} + */ + public static final int SHOW_DEFAULTS = SHOW_DECORATED_DISABLED; + + /** + * Show all the days + */ + public static final int SHOW_ALL = + SHOW_OTHER_MONTHS | SHOW_OUT_OF_RANGE | SHOW_DECORATED_DISABLED; + + /** + * Use this orientation to animate the title vertically + */ + public static final int VERTICAL = 0; + + /** + * Use this orientation to animate the title horizontally + */ + public static final int HORIZONTAL = 1; + + /** + * Default tile size in DIPs. This is used in cases where there is no tile size specificed and the + * view is set to {@linkplain ViewGroup.LayoutParams#WRAP_CONTENT WRAP_CONTENT} + */ + public static final int DEFAULT_TILE_SIZE_DP = 44; + private static final int DEFAULT_DAYS_IN_WEEK = 7; + private static final int DEFAULT_MAX_WEEKS = 6; + private static final int DAY_NAMES_ROW = 1; + + private final TitleChanger titleChanger; + + private final TextView title; + private final ImageView buttonPast; + private final ImageView buttonFuture; + private final CalendarPager pager; + private CalendarPagerAdapter adapter; + private CalendarDay currentMonth; + private LinearLayout topbar; + private CalendarMode calendarMode; + /** + * Used for the dynamic calendar height. + */ + private boolean mDynamicHeightEnabled; + + private final ArrayList dayViewDecorators = new ArrayList<>(); + + private final OnClickListener onClickListener = new OnClickListener() { @Override - public void onPageSelected(int position) { - titleChanger.setPreviousMonth(currentMonth); - currentMonth = adapter.getItem(position); - updateUi(); + public void onClick(View v) { + if (v == buttonFuture) { + pager.setCurrentItem(pager.getCurrentItem() + 1, true); + } else if (v == buttonPast) { + pager.setCurrentItem(pager.getCurrentItem() - 1, true); + } + } + }; + + private final ViewPager.OnPageChangeListener pageChangeListener = + new ViewPager.OnPageChangeListener() { + @Override + public void onPageSelected(int position) { + titleChanger.setPreviousMonth(currentMonth); + currentMonth = adapter.getItem(position); + updateUi(); + + dispatchOnMonthChanged(currentMonth); + } + + @Override + public void onPageScrollStateChanged(int state) { + } + + @Override + public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { + } + }; + + private CalendarDay minDate = null; + private CalendarDay maxDate = null; + + private OnDateSelectedListener listener; + private OnDateLongClickListener longClickListener; + private OnMonthChangedListener monthListener; + private OnRangeSelectedListener rangeListener; + + CharSequence calendarContentDescription; + private int accentColor = 0; + private int tileHeight = INVALID_TILE_DIMENSION; + private int tileWidth = INVALID_TILE_DIMENSION; + @SelectionMode + private int selectionMode = SELECTION_MODE_SINGLE; + private boolean allowClickDaysOutsideCurrentMonth = true; + private DayOfWeek firstDayOfWeek; + private boolean showWeekDays; + + private State state; + + public MaterialCalendarView(Context context) { + this(context, null); + } + + public MaterialCalendarView(Context context, AttributeSet attrs) { + super(context, attrs); - dispatchOnMonthChanged(currentMonth); + if (isInEditMode()) AndroidThreeTen.init(context); + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + //If we're on good Android versions, turn off clipping for cool effects + setClipToPadding(false); + setClipChildren(false); + } else { + //Old Android does not like _not_ clipping view pagers, we need to clip + setClipChildren(true); + setClipToPadding(true); } - @Override - public void onPageScrollStateChanged(int state) { + final LayoutInflater inflater = + (LayoutInflater) getContext().getSystemService(Service.LAYOUT_INFLATER_SERVICE); + final View content = inflater.inflate(R.layout.calendar_view, null, false); + + topbar = content.findViewById(R.id.header); + buttonPast = content.findViewById(R.id.previous); + title = content.findViewById(R.id.month_name); + buttonFuture = content.findViewById(R.id.next); + pager = new CalendarPager(getContext()); + + buttonPast.setOnClickListener(onClickListener); + buttonFuture.setOnClickListener(onClickListener); + + titleChanger = new TitleChanger(title); + + pager.setOnPageChangeListener(pageChangeListener); + pager.setPageTransformer(false, new ViewPager.PageTransformer() { + @Override + public void transformPage(View page, float position) { + position = (float) Math.sqrt(1 - Math.abs(position)); + page.setAlpha(position); + } + }); + + TypedArray a = context.getTheme() + .obtainStyledAttributes(attrs, R.styleable.MaterialCalendarView, 0, 0); + try { + int calendarModeIndex = a.getInteger( + R.styleable.MaterialCalendarView_mcv_calendarMode, + 0 + ); + int firstDayOfWeekInt = a.getInteger( + R.styleable.MaterialCalendarView_mcv_firstDayOfWeek, + -1 + ); + + titleChanger.setOrientation( + a.getInteger( + R.styleable.MaterialCalendarView_mcv_titleAnimationOrientation, + VERTICAL + )); + + if (firstDayOfWeekInt >= 1 && firstDayOfWeekInt <= 7) { + firstDayOfWeek = DayOfWeek.of(firstDayOfWeekInt); + } else { + firstDayOfWeek = WeekFields.of(Locale.getDefault()).getFirstDayOfWeek(); + } + + showWeekDays = a.getBoolean(R.styleable.MaterialCalendarView_mcv_showWeekDays, true); + + newState() + .setFirstDayOfWeek(firstDayOfWeek) + .setCalendarDisplayMode(CalendarMode.values()[calendarModeIndex]) + .setShowWeekDays(showWeekDays) + .commit(); + + setSelectionMode(a.getInteger( + R.styleable.MaterialCalendarView_mcv_selectionMode, + SELECTION_MODE_SINGLE + )); + + final int tileSize = a.getLayoutDimension( + R.styleable.MaterialCalendarView_mcv_tileSize, + INVALID_TILE_DIMENSION + ); + if (tileSize > INVALID_TILE_DIMENSION) { + setTileSize(tileSize); + } + + final int tileWidth = a.getLayoutDimension( + R.styleable.MaterialCalendarView_mcv_tileWidth, + INVALID_TILE_DIMENSION + ); + if (tileWidth > INVALID_TILE_DIMENSION) { + setTileWidth(tileWidth); + } + + final int tileHeight = a.getLayoutDimension( + R.styleable.MaterialCalendarView_mcv_tileHeight, + INVALID_TILE_DIMENSION + ); + if (tileHeight > INVALID_TILE_DIMENSION) { + setTileHeight(tileHeight); + } + + setLeftArrow( + a.getResourceId( + R.styleable.MaterialCalendarView_mcv_leftArrow, + R.drawable.mcv_action_previous + ) + ); + setRightArrow( + a.getResourceId( + R.styleable.MaterialCalendarView_mcv_rightArrow, + R.drawable.mcv_action_next + ) + ); + + setSelectionColor( + a.getColor( + R.styleable.MaterialCalendarView_mcv_selectionColor, + getThemeAccentColor(context) + ) + ); + + CharSequence[] array = a.getTextArray(R.styleable.MaterialCalendarView_mcv_weekDayLabels); + if (array != null) { + setWeekDayFormatter(new ArrayWeekDayFormatter(array)); + } + + array = a.getTextArray(R.styleable.MaterialCalendarView_mcv_monthLabels); + if (array != null) { + setTitleFormatter(new MonthArrayTitleFormatter(array)); + } + + setHeaderTextAppearance(a.getResourceId( + R.styleable.MaterialCalendarView_mcv_headerTextAppearance, + R.style.TextAppearance_MaterialCalendarWidget_Header + )); + setWeekDayTextAppearance(a.getResourceId( + R.styleable.MaterialCalendarView_mcv_weekDayTextAppearance, + R.style.TextAppearance_MaterialCalendarWidget_WeekDay + )); + setDateTextAppearance(a.getResourceId( + R.styleable.MaterialCalendarView_mcv_dateTextAppearance, + R.style.TextAppearance_MaterialCalendarWidget_Date + )); + //noinspection ResourceType + setShowOtherDates(a.getInteger( + R.styleable.MaterialCalendarView_mcv_showOtherDates, + SHOW_DEFAULTS + )); + + setAllowClickDaysOutsideCurrentMonth(a.getBoolean( + R.styleable.MaterialCalendarView_mcv_allowClickDaysOutsideCurrentMonth, + true + )); + } catch (Exception e) { + e.printStackTrace(); + } finally { + a.recycle(); } - @Override - public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { + // Adapter is created while parsing the TypedArray attrs, so setup has to happen after + setupChildren(); + + currentMonth = CalendarDay.today(); + setCurrentDate(currentMonth); + + if (isInEditMode()) { + removeView(pager); + MonthView monthView = new MonthView(this, currentMonth, getFirstDayOfWeek(), true); + monthView.setSelectionColor(getSelectionColor()); + monthView.setDateTextAppearance(adapter.getDateTextAppearance()); + monthView.setWeekDayTextAppearance(adapter.getWeekDayTextAppearance()); + monthView.setShowOtherDates(getShowOtherDates()); + addView(monthView, new LayoutParams(calendarMode.getVisibleWeeksCount() + DAY_NAMES_ROW)); } - }; - - private CalendarDay minDate = null; - private CalendarDay maxDate = null; - - private OnDateSelectedListener listener; - private OnDateLongClickListener longClickListener; - private OnMonthChangedListener monthListener; - private OnRangeSelectedListener rangeListener; - - CharSequence calendarContentDescription; - private int accentColor = 0; - private int tileHeight = INVALID_TILE_DIMENSION; - private int tileWidth = INVALID_TILE_DIMENSION; - @SelectionMode - private int selectionMode = SELECTION_MODE_SINGLE; - private boolean allowClickDaysOutsideCurrentMonth = true; - private DayOfWeek firstDayOfWeek; - private boolean showWeekDays; - - private State state; - - public MaterialCalendarView(Context context) { - this(context, null); - } - - public MaterialCalendarView(Context context, AttributeSet attrs) { - super(context, attrs); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - //If we're on good Android versions, turn off clipping for cool effects - setClipToPadding(false); - setClipChildren(false); - } else { - //Old Android does not like _not_ clipping view pagers, we need to clip - setClipChildren(true); - setClipToPadding(true); - } - - final LayoutInflater inflater = - (LayoutInflater) getContext().getSystemService(Service.LAYOUT_INFLATER_SERVICE); - final View content = inflater.inflate(R.layout.calendar_view, null, false); - - topbar = content.findViewById(R.id.header); - buttonPast = content.findViewById(R.id.previous); - title = content.findViewById(R.id.month_name); - buttonFuture = content.findViewById(R.id.next); - pager = new CalendarPager(getContext()); - - buttonPast.setOnClickListener(onClickListener); - buttonFuture.setOnClickListener(onClickListener); - - titleChanger = new TitleChanger(title); - - pager.setOnPageChangeListener(pageChangeListener); - pager.setPageTransformer(false, new ViewPager.PageTransformer() { - @Override - public void transformPage(View page, float position) { - position = (float) Math.sqrt(1 - Math.abs(position)); - page.setAlpha(position); - } - }); - - TypedArray a = context.getTheme() - .obtainStyledAttributes(attrs, R.styleable.MaterialCalendarView, 0, 0); - try { - int calendarModeIndex = a.getInteger( - R.styleable.MaterialCalendarView_mcv_calendarMode, - 0 - ); - int firstDayOfWeekInt = a.getInteger( - R.styleable.MaterialCalendarView_mcv_firstDayOfWeek, - -1 - ); - - titleChanger.setOrientation( - a.getInteger( - R.styleable.MaterialCalendarView_mcv_titleAnimationOrientation, - VERTICAL - )); - - if (firstDayOfWeekInt >= 1 && firstDayOfWeekInt <= 7) { - firstDayOfWeek = DayOfWeek.of(firstDayOfWeekInt); - } else { - firstDayOfWeek = WeekFields.of(Locale.getDefault()).getFirstDayOfWeek(); - } - - showWeekDays = a.getBoolean(R.styleable.MaterialCalendarView_mcv_showWeekDays, true); - - newState() - .setFirstDayOfWeek(firstDayOfWeek) - .setCalendarDisplayMode(CalendarMode.values()[calendarModeIndex]) - .setShowWeekDays(showWeekDays) - .commit(); - - setSelectionMode(a.getInteger( - R.styleable.MaterialCalendarView_mcv_selectionMode, - SELECTION_MODE_SINGLE - )); - - final int tileSize = a.getLayoutDimension( - R.styleable.MaterialCalendarView_mcv_tileSize, - INVALID_TILE_DIMENSION - ); - if (tileSize > INVALID_TILE_DIMENSION) { - setTileSize(tileSize); - } - - final int tileWidth = a.getLayoutDimension( - R.styleable.MaterialCalendarView_mcv_tileWidth, - INVALID_TILE_DIMENSION - ); - if (tileWidth > INVALID_TILE_DIMENSION) { - setTileWidth(tileWidth); - } - - final int tileHeight = a.getLayoutDimension( - R.styleable.MaterialCalendarView_mcv_tileHeight, - INVALID_TILE_DIMENSION - ); - if (tileHeight > INVALID_TILE_DIMENSION) { - setTileHeight(tileHeight); - } - - setLeftArrow( - a.getResourceId( - R.styleable.MaterialCalendarView_mcv_leftArrow, - R.drawable.mcv_action_previous - ) - ); - setRightArrow( - a.getResourceId( - R.styleable.MaterialCalendarView_mcv_rightArrow, - R.drawable.mcv_action_next - ) - ); - - setSelectionColor( - a.getColor( - R.styleable.MaterialCalendarView_mcv_selectionColor, - getThemeAccentColor(context) - ) - ); - - CharSequence[] array = a.getTextArray(R.styleable.MaterialCalendarView_mcv_weekDayLabels); - if (array != null) { - setWeekDayFormatter(new ArrayWeekDayFormatter(array)); - } - - array = a.getTextArray(R.styleable.MaterialCalendarView_mcv_monthLabels); - if (array != null) { - setTitleFormatter(new MonthArrayTitleFormatter(array)); - } - - setHeaderTextAppearance(a.getResourceId( - R.styleable.MaterialCalendarView_mcv_headerTextAppearance, - R.style.TextAppearance_MaterialCalendarWidget_Header - )); - setWeekDayTextAppearance(a.getResourceId( - R.styleable.MaterialCalendarView_mcv_weekDayTextAppearance, - R.style.TextAppearance_MaterialCalendarWidget_WeekDay - )); - setDateTextAppearance(a.getResourceId( - R.styleable.MaterialCalendarView_mcv_dateTextAppearance, - R.style.TextAppearance_MaterialCalendarWidget_Date - )); - //noinspection ResourceType - setShowOtherDates(a.getInteger( - R.styleable.MaterialCalendarView_mcv_showOtherDates, - SHOW_DEFAULTS - )); - - setAllowClickDaysOutsideCurrentMonth(a.getBoolean( - R.styleable.MaterialCalendarView_mcv_allowClickDaysOutsideCurrentMonth, - true - )); - } catch (Exception e) { - e.printStackTrace(); - } finally { - a.recycle(); - } - - // Adapter is created while parsing the TypedArray attrs, so setup has to happen after - setupChildren(); - - currentMonth = CalendarDay.today(); - setCurrentDate(currentMonth); - - if (isInEditMode()) { - removeView(pager); - MonthView monthView = new MonthView(this, currentMonth, getFirstDayOfWeek(), true); - monthView.setSelectionColor(getSelectionColor()); - monthView.setDateTextAppearance(adapter.getDateTextAppearance()); - monthView.setWeekDayTextAppearance(adapter.getWeekDayTextAppearance()); - monthView.setShowOtherDates(getShowOtherDates()); - addView(monthView, new LayoutParams(calendarMode.visibleWeeksCount + DAY_NAMES_ROW)); - } - } - - private void setupChildren() { - addView(topbar); - - pager.setId(R.id.mcv_pager); - pager.setOffscreenPageLimit(1); - int tileHeight = showWeekDays ? calendarMode.visibleWeeksCount + DAY_NAMES_ROW - : calendarMode.visibleWeeksCount; - addView(pager, new LayoutParams(tileHeight)); - } - - private void updateUi() { - titleChanger.change(currentMonth); - enableView(buttonPast, canGoBack()); - enableView(buttonFuture, canGoForward()); - } - - /** - * Change the selection mode of the calendar. The default mode is {@linkplain - * #SELECTION_MODE_SINGLE} - * - * @param mode the selection mode to change to. This must be one of - * {@linkplain #SELECTION_MODE_NONE}, {@linkplain #SELECTION_MODE_SINGLE}, - * {@linkplain #SELECTION_MODE_RANGE} or {@linkplain #SELECTION_MODE_MULTIPLE}. - * Unknown values will act as {@linkplain #SELECTION_MODE_SINGLE} - * @see #getSelectionMode() - * @see #SELECTION_MODE_NONE - * @see #SELECTION_MODE_SINGLE - * @see #SELECTION_MODE_MULTIPLE - * @see #SELECTION_MODE_RANGE - */ - public void setSelectionMode(final @SelectionMode int mode) { - final @SelectionMode int oldMode = this.selectionMode; - this.selectionMode = mode; - switch (mode) { - case SELECTION_MODE_RANGE: - clearSelection(); - break; - case SELECTION_MODE_MULTIPLE: - break; - case SELECTION_MODE_SINGLE: - if (oldMode == SELECTION_MODE_MULTIPLE || oldMode == SELECTION_MODE_RANGE) { - //We should only have one selection now, so we should pick one - List dates = getSelectedDates(); - if (!dates.isEmpty()) { - setSelectedDate(getSelectedDate()); - } + } + + private void setupChildren() { + addView(topbar); + + pager.setId(R.id.mcv_pager); + pager.setOffscreenPageLimit(1); + int tileHeight = showWeekDays ? calendarMode.getVisibleWeeksCount() + DAY_NAMES_ROW + : calendarMode.getVisibleWeeksCount(); + addView(pager, new LayoutParams(tileHeight)); + } + + private void updateUi() { + titleChanger.change(currentMonth); + enableView(buttonPast, canGoBack()); + enableView(buttonFuture, canGoForward()); + } + + /** + * Change the selection mode of the calendar. The default mode is {@linkplain + * #SELECTION_MODE_SINGLE} + * + * @param mode the selection mode to change to. This must be one of + * {@linkplain #SELECTION_MODE_NONE}, {@linkplain #SELECTION_MODE_SINGLE}, + * {@linkplain #SELECTION_MODE_RANGE} or {@linkplain #SELECTION_MODE_MULTIPLE}. + * Unknown values will act as {@linkplain #SELECTION_MODE_SINGLE} + * @see #getSelectionMode() + * @see #SELECTION_MODE_NONE + * @see #SELECTION_MODE_SINGLE + * @see #SELECTION_MODE_MULTIPLE + * @see #SELECTION_MODE_RANGE + */ + public void setSelectionMode(final @SelectionMode int mode) { + final @SelectionMode int oldMode = this.selectionMode; + this.selectionMode = mode; + switch (mode) { + case SELECTION_MODE_RANGE: + clearSelection(); + break; + case SELECTION_MODE_MULTIPLE: + break; + case SELECTION_MODE_SINGLE: + if (oldMode == SELECTION_MODE_MULTIPLE || oldMode == SELECTION_MODE_RANGE) { + //We should only have one selection now, so we should pick one + List dates = getSelectedDates(); + if (!dates.isEmpty()) { + setSelectedDate(getSelectedDate()); + } + } + break; + default: + case SELECTION_MODE_NONE: + this.selectionMode = SELECTION_MODE_NONE; + if (oldMode != SELECTION_MODE_NONE) { + //No selection! Clear out! + clearSelection(); + } + break; + } + + adapter.setSelectionEnabled(selectionMode != SELECTION_MODE_NONE); + } + + /** + * Go to previous month or week without using the button {@link #buttonPast}. Should only go to + * previous if {@link #canGoBack()} is true, meaning it's possible to go to the previous month + * or week. + */ + public void goToPrevious() { + if (canGoBack()) { + pager.setCurrentItem(pager.getCurrentItem() - 1, true); } - break; - default: - case SELECTION_MODE_NONE: - this.selectionMode = SELECTION_MODE_NONE; - if (oldMode != SELECTION_MODE_NONE) { - //No selection! Clear out! - clearSelection(); + } + + /** + * Go to next month or week without using the button {@link #buttonFuture}. Should only go to + * next if {@link #canGoForward()} is enabled, meaning it's possible to go to the next month or + * week. + */ + public void goToNext() { + if (canGoForward()) { + pager.setCurrentItem(pager.getCurrentItem() + 1, true); } - break; - } - - adapter.setSelectionEnabled(selectionMode != SELECTION_MODE_NONE); - } - - /** - * Go to previous month or week without using the button {@link #buttonPast}. Should only go to - * previous if {@link #canGoBack()} is true, meaning it's possible to go to the previous month - * or week. - */ - public void goToPrevious() { - if (canGoBack()) { - pager.setCurrentItem(pager.getCurrentItem() - 1, true); - } - } - - /** - * Go to next month or week without using the button {@link #buttonFuture}. Should only go to - * next if {@link #canGoForward()} is enabled, meaning it's possible to go to the next month or - * week. - */ - public void goToNext() { - if (canGoForward()) { - pager.setCurrentItem(pager.getCurrentItem() + 1, true); - } - } - - /** - * Get the current selection mode. The default mode is {@linkplain #SELECTION_MODE_SINGLE} - * - * @return the current selection mode - * @see #setSelectionMode(int) - * @see #SELECTION_MODE_NONE - * @see #SELECTION_MODE_SINGLE - * @see #SELECTION_MODE_MULTIPLE - * @see #SELECTION_MODE_RANGE - */ - @SelectionMode - public int getSelectionMode() { - return selectionMode; - } - - /** - * Use {@link #getTileWidth()} or {@link #getTileHeight()} instead. This method is deprecated - * and will just return the largest of the two sizes. - * - * @return tile height or width, whichever is larger - */ - @Deprecated - public int getTileSize() { - return Math.max(tileHeight, tileWidth); - } - - /** - * Set the size of each tile that makes up the calendar. - * Each day is 1 tile, so the widget is 7 tiles wide and 7 or 8 tiles tall - * depending on the visibility of the {@link #topbar}. - * - * @param size the new size for each tile in pixels - */ - public void setTileSize(int size) { - this.tileWidth = size; - this.tileHeight = size; - requestLayout(); - } - - /** - * @param tileSizeDp the new size for each tile in dips - * @see #setTileSize(int) - */ - public void setTileSizeDp(int tileSizeDp) { - setTileSize(dpToPx(tileSizeDp)); - } - - /** - * @return the height of tiles in pixels - */ - public int getTileHeight() { - return tileHeight; - } - - /** - * Set the height of each tile that makes up the calendar. - * - * @param height the new height for each tile in pixels - */ - public void setTileHeight(int height) { - this.tileHeight = height; - requestLayout(); - } - - /** - * @param tileHeightDp the new height for each tile in dips - * @see #setTileHeight(int) - */ - public void setTileHeightDp(int tileHeightDp) { - setTileHeight(dpToPx(tileHeightDp)); - } - - /** - * @return the width of tiles in pixels - */ - public int getTileWidth() { - return tileWidth; - } - - /** - * Set the width of each tile that makes up the calendar. - * - * @param width the new width for each tile in pixels - */ - public void setTileWidth(int width) { - this.tileWidth = width; - requestLayout(); - } - - /** - * @param tileWidthDp the new width for each tile in dips - * @see #setTileWidth(int) - */ - public void setTileWidthDp(int tileWidthDp) { - setTileWidth(dpToPx(tileWidthDp)); - } - - private int dpToPx(int dp) { - return (int) TypedValue.applyDimension( - TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics() - ); - } - - /** - * Whether the pager can page forward, meaning the future month is enabled. - * - * @return true if there is a future month that can be shown - */ - public boolean canGoForward() { - return pager.getCurrentItem() < (adapter.getCount() - 1); - } - - /** - * Whether the pager can page backward, meaning the previous month is enabled. - * - * @return true if there is a previous month that can be shown - */ - public boolean canGoBack() { - return pager.getCurrentItem() > 0; - } - - /** - * Pass all touch events to the pager so scrolling works on the edges of the calendar view. - */ - @Override - public boolean onTouchEvent(MotionEvent event) { - return pager.dispatchTouchEvent(event); - } - - /** - * @return the color used for the selection - */ - public int getSelectionColor() { - return accentColor; - } - - /** - * @param color The selection color - */ - public void setSelectionColor(int color) { - if (color == 0) { - if (!isInEditMode()) { - return; - } else { - color = Color.GRAY; - } - } - accentColor = color; - adapter.setSelectionColor(color); - invalidate(); - } - - /** - * Set content description for button past - * - * @param description String to use as content description - */ - public void setContentDescriptionArrowPast(final CharSequence description) { - buttonPast.setContentDescription(description); - } - - /** - * Set content description for button future - * - * @param description String to use as content description - */ - public void setContentDescriptionArrowFuture(final CharSequence description) { - buttonFuture.setContentDescription(description); - } - - /** - * Set content description for calendar - * - * @param description String to use as content description - */ - public void setContentDescriptionCalendar(final CharSequence description) { - calendarContentDescription = description; - } - - /** - * Get content description for calendar - * - * @return calendar's content description - */ - public CharSequence getCalendarContentDescription() { - return calendarContentDescription != null - ? calendarContentDescription - : getContext().getString(R.string.calendar); - } - - /** - * Set a formatter for day content description. - * - * @param formatter the new formatter, null for default - */ - public void setDayFormatterContentDescription(DayFormatter formatter) { - adapter.setDayFormatterContentDescription(formatter); - } - - /** - * @return icon used for the left arrow - */ - public Drawable getLeftArrow() { - return buttonPast.getDrawable(); - } - - /** - * @param icon the new icon to use for the left paging arrow - */ - public void setLeftArrow(@DrawableRes final int icon) { - buttonPast.setImageResource(icon); - } - - /** - * @return icon used for the right arrow - */ - public Drawable getRightArrow() { - return buttonFuture.getDrawable(); - } - - /** - * @param icon the new icon to use for the right paging arrow - */ - public void setRightArrow(@DrawableRes final int icon) { - buttonFuture.setImageResource(icon); - } - - /** - * @param resourceId The text appearance resource id. - */ - public void setHeaderTextAppearance(int resourceId) { - title.setTextAppearance(getContext(), resourceId); - } - - /** - * @param resourceId The text appearance resource id. - */ - public void setDateTextAppearance(int resourceId) { - adapter.setDateTextAppearance(resourceId); - } - - /** - * @param resourceId The text appearance resource id. - */ - public void setWeekDayTextAppearance(int resourceId) { - adapter.setWeekDayTextAppearance(resourceId); - } - - /** - * Get the currently selected date, or null if no selection. Depending on the selection mode, - * you might get different results. - * - *

For {@link #SELECTION_MODE_SINGLE}, returns the selected date.

- *

For {@link #SELECTION_MODE_MULTIPLE}, returns the last date selected.

- *

For {@link #SELECTION_MODE_RANGE}, returns the last date of the range. In most cases, you - * should probably be using {@link #getSelectedDates()}.

- *

For {@link #SELECTION_MODE_NONE}, returns null.

- * - * @return The selected day, or null if no selection. If in multiple selection mode, this - * will return the last date of the list of selected dates. - * @see MaterialCalendarView#getSelectedDates() - */ - @Nullable public CalendarDay getSelectedDate() { - List dates = adapter.getSelectedDates(); - if (dates.isEmpty()) { - return null; - } else { - return dates.get(dates.size() - 1); - } - } - - /** - * Return the list of currently selected dates. Mostly useful for {@link #SELECTION_MODE_MULTIPLE} - * and {@link #SELECTION_MODE_RANGE}. For the other modes, check {@link #getSelectedDate()}. - * - *

For {@link #SELECTION_MODE_MULTIPLE}, returns the list in the order of selection.

- *

For {@link #SELECTION_MODE_RANGE}, returns the range of dates ordered chronologically.

- * - * @return All of the currently selected dates. - * @see MaterialCalendarView#getSelectedDate() - */ - @NonNull public List getSelectedDates() { - return adapter.getSelectedDates(); - } - - /** - * Clear the currently selected date(s) - */ - public void clearSelection() { - List dates = getSelectedDates(); - adapter.clearSelections(); - for (CalendarDay day : dates) { - dispatchOnDateSelected(day, false); - } - } - - /** - * @param date a Date set to a day to select. Null to clear selection - */ - public void setSelectedDate(@Nullable LocalDate date) { - setSelectedDate(CalendarDay.from(date)); - } - - /** - * @param date a Date to set as selected. Null to clear selection - */ - public void setSelectedDate(@Nullable CalendarDay date) { - clearSelection(); - if (date != null) { - setDateSelected(date, true); - } - } - - /** - * @param day a CalendarDay to change. Passing null does nothing - * @param selected true if day should be selected, false to deselect - */ - public void setDateSelected(@Nullable CalendarDay day, boolean selected) { - if (day == null) { - return; - } - adapter.setDateSelected(day, selected); - } - - /** - * Get the current first day of the month in month mode, or the first visible day of the - * currently visible week. - * - * For example, in week mode, if the week is July 29th, 2018 to August 4th, 2018, - * this will return July 29th, 2018. If in month mode and the month is august, then this method - * will return August 1st, 2018. - * - * @return The current month or week shown, will be set to first day of the month in month mode, - * or the first visible day for a week. - */ - public CalendarDay getCurrentDate() { - return adapter.getItem(pager.getCurrentItem()); - } - - /** - * Set the calendar to a specific month or week based on a date. - * - * In month mode, the calendar will be set to the corresponding month. - * - * In week mode, the calendar will be set to the corresponding week. - * - * @param calendar a Calendar set to a day to focus the calendar on. Null will do nothing - */ - public void setCurrentDate(@Nullable LocalDate calendar) { - setCurrentDate(CalendarDay.from(calendar)); - } - - /** - * Set the calendar to a specific month or week based on a date. - * - * In month mode, the calendar will be set to the corresponding month. - * - * In week mode, the calendar will be set to the corresponding week. - * - * @param day a CalendarDay to focus the calendar on. Null will do nothing - */ - public void setCurrentDate(@Nullable CalendarDay day) { - setCurrentDate(day, true); - } - - /** - * Set the calendar to a specific month or week based on a date. - * - * In month mode, the calendar will be set to the corresponding month. - * - * In week mode, the calendar will be set to the corresponding week. - * - * @param day a CalendarDay to focus the calendar on. Null will do nothing - * @param useSmoothScroll use smooth scroll when changing months. - */ - public void setCurrentDate(@Nullable CalendarDay day, boolean useSmoothScroll) { - if (day == null) { - return; - } - int index = adapter.getIndexForDay(day); - pager.setCurrentItem(index, useSmoothScroll); - updateUi(); - } - - /** - * @return the minimum selectable date for the calendar, if any - */ - public CalendarDay getMinimumDate() { - return minDate; - } - - /** - * @return the maximum selectable date for the calendar, if any - */ - public CalendarDay getMaximumDate() { - return maxDate; - } - - /** - * The default value is {@link #SHOW_DEFAULTS}, which currently is just {@link - * #SHOW_DECORATED_DISABLED}. - * This means that the default visible days are of the current month, in the min-max range. - * - * @param showOtherDates flags for showing non-enabled dates - * @see #SHOW_ALL - * @see #SHOW_NONE - * @see #SHOW_DEFAULTS - * @see #SHOW_OTHER_MONTHS - * @see #SHOW_OUT_OF_RANGE - * @see #SHOW_DECORATED_DISABLED - */ - public void setShowOtherDates(@ShowOtherDates int showOtherDates) { - adapter.setShowOtherDates(showOtherDates); - } - - /** - * Allow the user to click on dates from other months that are not out of range. Go to next or - * previous month if a day outside the current month is clicked. The day still need to be - * enabled to be selected. - * Default value is true. Should be used with {@link #SHOW_OTHER_MONTHS}. - * - * @param enabled True to allow the user to click on a day outside current month displayed - */ - public void setAllowClickDaysOutsideCurrentMonth(final boolean enabled) { - this.allowClickDaysOutsideCurrentMonth = enabled; - } - - /** - * Set a formatter for weekday labels. - * - * @param formatter the new formatter, null for default - */ - public void setWeekDayFormatter(WeekDayFormatter formatter) { - adapter.setWeekDayFormatter(formatter == null ? WeekDayFormatter.DEFAULT : formatter); - } - - /** - * Set a formatter for day labels. - * - * @param formatter the new formatter, null for default - */ - public void setDayFormatter(DayFormatter formatter) { - adapter.setDayFormatter(formatter == null ? DayFormatter.DEFAULT : formatter); - } - - /** - * Set a {@linkplain com.prolificinteractive.materialcalendarview.format.WeekDayFormatter} - * with the provided week day labels - * - * @param weekDayLabels Labels to use for the days of the week - * @see com.prolificinteractive.materialcalendarview.format.ArrayWeekDayFormatter - * @see #setWeekDayFormatter(com.prolificinteractive.materialcalendarview.format.WeekDayFormatter) - */ - public void setWeekDayLabels(CharSequence[] weekDayLabels) { - setWeekDayFormatter(new ArrayWeekDayFormatter(weekDayLabels)); - } - - /** - * Set a {@linkplain com.prolificinteractive.materialcalendarview.format.WeekDayFormatter} - * with the provided week day labels - * - * @param arrayRes String array resource of week day labels - * @see com.prolificinteractive.materialcalendarview.format.ArrayWeekDayFormatter - * @see #setWeekDayFormatter(com.prolificinteractive.materialcalendarview.format.WeekDayFormatter) - */ - public void setWeekDayLabels(@ArrayRes int arrayRes) { - setWeekDayLabels(getResources().getTextArray(arrayRes)); - } - - /** - * @return int of flags used for showing non-enabled dates - * @see #SHOW_ALL - * @see #SHOW_NONE - * @see #SHOW_DEFAULTS - * @see #SHOW_OTHER_MONTHS - * @see #SHOW_OUT_OF_RANGE - * @see #SHOW_DECORATED_DISABLED - */ - @ShowOtherDates - public int getShowOtherDates() { - return adapter.getShowOtherDates(); - } - - /** - * @return true if allow click on days outside current month displayed - */ - public boolean allowClickDaysOutsideCurrentMonth() { - return allowClickDaysOutsideCurrentMonth; - } - - /** - * @return true if the week days names are shown - */ - public boolean isShowWeekDays() { - return showWeekDays; - } - - /** - * Set a custom formatter for the month/year title - * - * @param titleFormatter new formatter to use, null to use default formatter - */ - public void setTitleFormatter(@Nullable TitleFormatter titleFormatter) { - titleChanger.setTitleFormatter(titleFormatter); - adapter.setTitleFormatter(titleFormatter); - updateUi(); - } - - /** - * Set a {@linkplain com.prolificinteractive.materialcalendarview.format.TitleFormatter} - * using the provided month labels - * - * @param monthLabels month labels to use - * @see com.prolificinteractive.materialcalendarview.format.MonthArrayTitleFormatter - * @see #setTitleFormatter(com.prolificinteractive.materialcalendarview.format.TitleFormatter) - */ - public void setTitleMonths(CharSequence[] monthLabels) { - setTitleFormatter(new MonthArrayTitleFormatter(monthLabels)); - } - - /** - * Set a {@linkplain com.prolificinteractive.materialcalendarview.format.TitleFormatter} - * using the provided month labels - * - * @param arrayRes String array resource of month labels to use - * @see com.prolificinteractive.materialcalendarview.format.MonthArrayTitleFormatter - * @see #setTitleFormatter(com.prolificinteractive.materialcalendarview.format.TitleFormatter) - */ - public void setTitleMonths(@ArrayRes int arrayRes) { - setTitleMonths(getResources().getTextArray(arrayRes)); - } - - /** - * Change the title animation orientation to have a different look and feel. - * - * @param orientation {@link MaterialCalendarView#VERTICAL} or {@link - * MaterialCalendarView#HORIZONTAL} - */ - public void setTitleAnimationOrientation(final int orientation) { - titleChanger.setOrientation(orientation); - } - - /** - * Get the orientation of the animation of the title. - * - * @return Title animation orientation {@link MaterialCalendarView#VERTICAL} or {@link - * MaterialCalendarView#HORIZONTAL} - */ - public int getTitleAnimationOrientation() { - return titleChanger.getOrientation(); - } - - /** - * Sets the visibility {@link #topbar}, which contains - * the previous month button {@link #buttonPast}, next month button {@link #buttonFuture}, - * and the month title {@link #title}. - * - * @param visible Boolean indicating if the topbar is visible - */ - public void setTopbarVisible(boolean visible) { - topbar.setVisibility(visible ? View.VISIBLE : View.GONE); - requestLayout(); - } - - /** - * @return true if the topbar is visible - */ - public boolean getTopbarVisible() { - return topbar.getVisibility() == View.VISIBLE; - } - - /** - * Get the current {@link CalendarMode} set of the Calendar. - * - * @return Whichever mode the calendar is currently in. - */ - public CalendarMode getCalendarMode() { - return calendarMode; - } - - @Override - protected Parcelable onSaveInstanceState() { - SavedState ss = new SavedState(super.onSaveInstanceState()); - ss.showOtherDates = getShowOtherDates(); - ss.allowClickDaysOutsideCurrentMonth = allowClickDaysOutsideCurrentMonth(); - ss.minDate = getMinimumDate(); - ss.maxDate = getMaximumDate(); - ss.selectedDates = getSelectedDates(); - ss.selectionMode = getSelectionMode(); - ss.topbarVisible = getTopbarVisible(); - ss.dynamicHeightEnabled = mDynamicHeightEnabled; - ss.currentMonth = currentMonth; - ss.cacheCurrentPosition = state.cacheCurrentPosition; - return ss; - } - - @Override - protected void onRestoreInstanceState(Parcelable state) { - SavedState ss = (SavedState) state; - super.onRestoreInstanceState(ss.getSuperState()); - state().edit() - .setMinimumDate(ss.minDate) - .setMaximumDate(ss.maxDate) - .isCacheCalendarPositionEnabled(ss.cacheCurrentPosition) - .commit(); - - setShowOtherDates(ss.showOtherDates); - setAllowClickDaysOutsideCurrentMonth(ss.allowClickDaysOutsideCurrentMonth); - clearSelection(); - for (CalendarDay calendarDay : ss.selectedDates) { - setDateSelected(calendarDay, true); - } - setTopbarVisible(ss.topbarVisible); - setSelectionMode(ss.selectionMode); - setDynamicHeightEnabled(ss.dynamicHeightEnabled); - setCurrentDate(ss.currentMonth); - } - - @Override - protected void dispatchSaveInstanceState(@NonNull SparseArray container) { - dispatchFreezeSelfOnly(container); - } - - @Override - protected void dispatchRestoreInstanceState(@NonNull SparseArray container) { - dispatchThawSelfOnly(container); - } - - private void setRangeDates(CalendarDay min, CalendarDay max) { - CalendarDay c = currentMonth; - adapter.setRangeDates(min, max); - currentMonth = c; - if (min != null) { - currentMonth = min.isAfter(currentMonth) ? min : currentMonth; - } - int position = adapter.getIndexForDay(c); - pager.setCurrentItem(position, false); - updateUi(); - } - - public static class SavedState extends BaseSavedState { - - int showOtherDates = SHOW_DEFAULTS; - boolean allowClickDaysOutsideCurrentMonth = true; - CalendarDay minDate = null; - CalendarDay maxDate = null; - List selectedDates = new ArrayList<>(); - boolean topbarVisible = true; - int selectionMode = SELECTION_MODE_SINGLE; - boolean dynamicHeightEnabled = false; - CalendarDay currentMonth = null; - boolean cacheCurrentPosition; - - SavedState(Parcelable superState) { - super(superState); } + /** + * Get the current selection mode. The default mode is {@linkplain #SELECTION_MODE_SINGLE} + * + * @return the current selection mode + * @see #setSelectionMode(int) + * @see #SELECTION_MODE_NONE + * @see #SELECTION_MODE_SINGLE + * @see #SELECTION_MODE_MULTIPLE + * @see #SELECTION_MODE_RANGE + */ + @SelectionMode + public int getSelectionMode() { + return selectionMode; + } + + /** + * Use {@link #getTileWidth()} or {@link #getTileHeight()} instead. This method is deprecated + * and will just return the largest of the two sizes. + * + * @return tile height or width, whichever is larger + */ + @Deprecated + public int getTileSize() { + return Math.max(tileHeight, tileWidth); + } + + /** + * Set the size of each tile that makes up the calendar. + * Each day is 1 tile, so the widget is 7 tiles wide and 7 or 8 tiles tall + * depending on the visibility of the {@link #topbar}. + * + * @param size the new size for each tile in pixels + */ + public void setTileSize(int size) { + this.tileWidth = size; + this.tileHeight = size; + requestLayout(); + } + + /** + * @param tileSizeDp the new size for each tile in dips + * @see #setTileSize(int) + */ + public void setTileSizeDp(int tileSizeDp) { + setTileSize(dpToPx(tileSizeDp)); + } + + /** + * @return the height of tiles in pixels + */ + public int getTileHeight() { + return tileHeight; + } + + /** + * Set the height of each tile that makes up the calendar. + * + * @param height the new height for each tile in pixels + */ + public void setTileHeight(int height) { + this.tileHeight = height; + requestLayout(); + } + + /** + * @param tileHeightDp the new height for each tile in dips + * @see #setTileHeight(int) + */ + public void setTileHeightDp(int tileHeightDp) { + setTileHeight(dpToPx(tileHeightDp)); + } + + /** + * @return the width of tiles in pixels + */ + public int getTileWidth() { + return tileWidth; + } + + /** + * Set the width of each tile that makes up the calendar. + * + * @param width the new width for each tile in pixels + */ + public void setTileWidth(int width) { + this.tileWidth = width; + requestLayout(); + } + + /** + * @param tileWidthDp the new width for each tile in dips + * @see #setTileWidth(int) + */ + public void setTileWidthDp(int tileWidthDp) { + setTileWidth(dpToPx(tileWidthDp)); + } + + private int dpToPx(int dp) { + return (int) TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics() + ); + } + + /** + * Whether the pager can page forward, meaning the future month is enabled. + * + * @return true if there is a future month that can be shown + */ + public boolean canGoForward() { + return pager.getCurrentItem() < (adapter.getCount() - 1); + } + + /** + * Whether the pager can page backward, meaning the previous month is enabled. + * + * @return true if there is a previous month that can be shown + */ + public boolean canGoBack() { + return pager.getCurrentItem() > 0; + } + + /** + * Pass all touch events to the pager so scrolling works on the edges of the calendar view. + */ @Override - public void writeToParcel(@NonNull Parcel out, int flags) { - super.writeToParcel(out, flags); - out.writeInt(showOtherDates); - out.writeByte((byte) (allowClickDaysOutsideCurrentMonth ? 1 : 0)); - out.writeParcelable(minDate, 0); - out.writeParcelable(maxDate, 0); - out.writeTypedList(selectedDates); - out.writeInt(topbarVisible ? 1 : 0); - out.writeInt(selectionMode); - out.writeInt(dynamicHeightEnabled ? 1 : 0); - out.writeParcelable(currentMonth, 0); - out.writeByte((byte) (cacheCurrentPosition ? 1 : 0)); - } - - public static final Parcelable.Creator CREATOR - = new Parcelable.Creator() { - public SavedState createFromParcel(Parcel in) { - return new SavedState(in); - } - - public SavedState[] newArray(int size) { - return new SavedState[size]; - } - }; + public boolean onTouchEvent(MotionEvent event) { + return pager.dispatchTouchEvent(event); + } - private SavedState(Parcel in) { - super(in); - showOtherDates = in.readInt(); - allowClickDaysOutsideCurrentMonth = in.readByte() != 0; - ClassLoader loader = CalendarDay.class.getClassLoader(); - minDate = in.readParcelable(loader); - maxDate = in.readParcelable(loader); - in.readTypedList(selectedDates, CalendarDay.CREATOR); - topbarVisible = in.readInt() == 1; - selectionMode = in.readInt(); - dynamicHeightEnabled = in.readInt() == 1; - currentMonth = in.readParcelable(loader); - cacheCurrentPosition = in.readByte() != 0; - } - } - - private static int getThemeAccentColor(Context context) { - int colorAttr; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - colorAttr = android.R.attr.colorAccent; - } else { - //Get colorAccent defined for AppCompat - colorAttr = - context.getResources().getIdentifier("colorAccent", "attr", context.getPackageName()); - } - TypedValue outValue = new TypedValue(); - context.getTheme().resolveAttribute(colorAttr, outValue, true); - return outValue.data; - } - - /** - * @return The first day of the week as a {@linkplain Calendar} day constant. - */ - public DayOfWeek getFirstDayOfWeek() { - return firstDayOfWeek; - } - - /** - * By default, the calendar will take up all the space needed to show any month (6 rows). - * By enabling dynamic height, the view will change height dependant on the visible month. - *

- * This means months that only need 5 or 4 rows to show the entire month will only take up - * that many rows, and will grow and shrink as necessary. - * - * @param useDynamicHeight true to have the view different heights based on the visible month - */ - public void setDynamicHeightEnabled(boolean useDynamicHeight) { - this.mDynamicHeightEnabled = useDynamicHeight; - } - - /** - * @return the dynamic height state - true if enabled. - */ - public boolean isDynamicHeightEnabled() { - return mDynamicHeightEnabled; - } - - /** - * Add a collection of day decorators - * - * @param decorators decorators to add - */ - public void addDecorators(Collection decorators) { - if (decorators == null) { - return; - } - - dayViewDecorators.addAll(decorators); - adapter.setDecorators(dayViewDecorators); - } - - /** - * Add several day decorators - * - * @param decorators decorators to add - */ - public void addDecorators(DayViewDecorator... decorators) { - addDecorators(Arrays.asList(decorators)); - } - - /** - * Add a day decorator - * - * @param decorator decorator to add - */ - public void addDecorator(DayViewDecorator decorator) { - if (decorator == null) { - return; - } - dayViewDecorators.add(decorator); - adapter.setDecorators(dayViewDecorators); - } - - /** - * Remove all decorators - */ - public void removeDecorators() { - dayViewDecorators.clear(); - adapter.setDecorators(dayViewDecorators); - } - - /** - * Remove a specific decorator instance. Same rules as {@linkplain List#remove(Object)} - * - * @param decorator decorator to remove - */ - public void removeDecorator(DayViewDecorator decorator) { - dayViewDecorators.remove(decorator); - adapter.setDecorators(dayViewDecorators); - } - - /** - * Invalidate decorators after one has changed internally. That is, if a decorator mutates, you - * should call this method to update the widget. - */ - public void invalidateDecorators() { - adapter.invalidateDecorators(); - } - - /* - * Listener/Callback Code - */ - - /** - * Sets the listener to be notified upon selected date changes. - * - * @param listener thing to be notified - */ - public void setOnDateChangedListener(OnDateSelectedListener listener) { - this.listener = listener; - } - - /** - * Sets the listener to be notified upon long clicks on dates. - * - * @param longClickListener thing to be notified - */ - public void setOnDateLongClickListener(OnDateLongClickListener longClickListener) { - this.longClickListener = longClickListener; - } - - /** - * Sets the listener to be notified upon month changes. - * - * @param listener thing to be notified - */ - public void setOnMonthChangedListener(OnMonthChangedListener listener) { - this.monthListener = listener; - } - - /** - * Sets the listener to be notified upon a range has been selected. - * - * @param listener thing to be notified - */ - public void setOnRangeSelectedListener(OnRangeSelectedListener listener) { - this.rangeListener = listener; - } - - /** - * Add listener to the title or null to remove it. - * - * @param listener Listener to be notified. - */ - public void setOnTitleClickListener(final OnClickListener listener) { - title.setOnClickListener(listener); - } - - /** - * Dispatch date change events to a listener, if set - * - * @param day the day that was selected - * @param selected true if the day is now currently selected, false otherwise - */ - protected void dispatchOnDateSelected(final CalendarDay day, final boolean selected) { - if (listener != null) { - listener.onDateSelected(MaterialCalendarView.this, day, selected); - } - } - - /** - * Dispatch a range of days to a range listener, if set, ordered chronologically. - * - * @param days Enclosing days ordered from first to last day. - */ - protected void dispatchOnRangeSelected(@NonNull final List days) { - if (rangeListener != null) { - rangeListener.onRangeSelected(MaterialCalendarView.this, days); - } - } - - /** - * Dispatch date change events to a listener, if set - * - * @param day first day of the new month - */ - protected void dispatchOnMonthChanged(final CalendarDay day) { - if (monthListener != null) { - monthListener.onMonthChanged(MaterialCalendarView.this, day); - } - } - - /** - * Call by {@link CalendarPagerView} to indicate that a day was clicked and we should handle it. - * This method will always process the click to the selected date. - * - * @param date date of the day that was clicked - * @param nowSelected true if the date is now selected, false otherwise - */ - protected void onDateClicked(@NonNull CalendarDay date, boolean nowSelected) { - switch (selectionMode) { - case SELECTION_MODE_MULTIPLE: { - adapter.setDateSelected(date, nowSelected); - dispatchOnDateSelected(date, nowSelected); - } - break; - case SELECTION_MODE_RANGE: { - final List currentSelection = adapter.getSelectedDates(); - - if (currentSelection.size() == 0) { - // Selecting the first date of a range - adapter.setDateSelected(date, nowSelected); - dispatchOnDateSelected(date, nowSelected); - } else if (currentSelection.size() == 1) { - // Selecting the second date of a range - final CalendarDay firstDaySelected = currentSelection.get(0); - if (firstDaySelected.equals(date)) { - // Right now, we are not supporting a range of one day, so we are removing the day instead. - adapter.setDateSelected(date, nowSelected); - dispatchOnDateSelected(date, nowSelected); - } else if (firstDaySelected.isAfter(date)) { - // Selecting a range, dispatching in reverse order... - adapter.selectRange(date, firstDaySelected); - dispatchOnRangeSelected(adapter.getSelectedDates()); - } else { - // Selecting a range, dispatching in order... - adapter.selectRange(firstDaySelected, date); - dispatchOnRangeSelected(adapter.getSelectedDates()); - } - } else { - // Clearing selection and making a selection of the new date. - adapter.clearSelections(); - adapter.setDateSelected(date, nowSelected); - dispatchOnDateSelected(date, nowSelected); + /** + * @return the color used for the selection + */ + public int getSelectionColor() { + return accentColor; + } + + /** + * @param color The selection color + */ + public void setSelectionColor(int color) { + if (color == 0) { + if (!isInEditMode()) { + return; + } else { + color = Color.GRAY; + } } - } - break; - default: - case SELECTION_MODE_SINGLE: { - adapter.clearSelections(); - adapter.setDateSelected(date, true); - dispatchOnDateSelected(date, true); - } - break; - } - } - - /** - * Select a fresh range of date including first day and last day. - * - * @param firstDay first day of the range to select - * @param lastDay last day of the range to select - */ - public void selectRange(final CalendarDay firstDay, final CalendarDay lastDay) { - if (firstDay == null || lastDay == null) { - return; - } else if (firstDay.isAfter(lastDay)) { - adapter.selectRange(lastDay, firstDay); - dispatchOnRangeSelected(adapter.getSelectedDates()); - } else { - adapter.selectRange(firstDay, lastDay); - dispatchOnRangeSelected(adapter.getSelectedDates()); - } - } - - /** - * Call by {@link CalendarPagerView} to indicate that a day was clicked and we should handle it - */ - protected void onDateClicked(final DayView dayView) { - final CalendarDay currentDate = getCurrentDate(); - final CalendarDay selectedDate = dayView.getDate(); - final int currentMonth = currentDate.getMonth(); - final int selectedMonth = selectedDate.getMonth(); - - if (calendarMode == CalendarMode.MONTHS - && allowClickDaysOutsideCurrentMonth - && currentMonth != selectedMonth) { - if (currentDate.isAfter(selectedDate)) { - goToPrevious(); - } else if (currentDate.isBefore(selectedDate)) { - goToNext(); - } - } - onDateClicked(dayView.getDate(), !dayView.isChecked()); - } - - /** - * Call by {@link CalendarPagerView} to indicate that a day was long clicked and we should handle - * it - */ - protected void onDateLongClicked(final DayView dayView) { - if (longClickListener != null) { - longClickListener.onDateLongClick(MaterialCalendarView.this, dayView.getDate()); - } - } - - /** - * Called by the adapter for cases when changes in state result in dates being unselected - * - * @param date date that should be de-selected - */ - protected void onDateUnselected(CalendarDay date) { - dispatchOnDateSelected(date, false); - } - - /* - * Show Other Dates Utils - */ - - /** - * @param showOtherDates int flag for show other dates - * @return true if the other months flag is set - */ - public static boolean showOtherMonths(@ShowOtherDates int showOtherDates) { - return (showOtherDates & SHOW_OTHER_MONTHS) != 0; - } - - /** - * @param showOtherDates int flag for show other dates - * @return true if the out of range flag is set - */ - public static boolean showOutOfRange(@ShowOtherDates int showOtherDates) { - return (showOtherDates & SHOW_OUT_OF_RANGE) != 0; - } - - /** - * @param showOtherDates int flag for show other dates - * @return true if the decorated disabled flag is set - */ - public static boolean showDecoratedDisabled(@ShowOtherDates int showOtherDates) { - return (showOtherDates & SHOW_DECORATED_DISABLED) != 0; - } - - /* - * Custom ViewGroup Code - */ - - /** - * {@inheritDoc} - */ - @Override - protected LayoutParams generateDefaultLayoutParams() { - return new LayoutParams(1); - } - - /** - * {@inheritDoc} - */ - @Override - protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { - final int specWidthSize = MeasureSpec.getSize(widthMeasureSpec); - final int specWidthMode = MeasureSpec.getMode(widthMeasureSpec); - final int specHeightSize = MeasureSpec.getSize(heightMeasureSpec); - final int specHeightMode = MeasureSpec.getMode(heightMeasureSpec); - - //We need to disregard padding for a while. This will be added back later - final int desiredWidth = specWidthSize - getPaddingLeft() - getPaddingRight(); - final int desiredHeight = specHeightSize - getPaddingTop() - getPaddingBottom(); - - final int weekCount = getWeekCountBasedOnMode(); - - final int viewTileHeight = getTopbarVisible() ? (weekCount + 1) : weekCount; - - //Calculate independent tile sizes for later - int desiredTileWidth = desiredWidth / DEFAULT_DAYS_IN_WEEK; - int desiredTileHeight = desiredHeight / viewTileHeight; - - int measureTileSize = -1; - int measureTileWidth = -1; - int measureTileHeight = -1; - - if (this.tileWidth != INVALID_TILE_DIMENSION || this.tileHeight != INVALID_TILE_DIMENSION) { - if (this.tileWidth > 0) { - //We have a tileWidth set, we should use that - measureTileWidth = this.tileWidth; - } else { - measureTileWidth = desiredTileWidth; - } - if (this.tileHeight > 0) { - //We have a tileHeight set, we should use that - measureTileHeight = this.tileHeight; - } else { - measureTileHeight = desiredTileHeight; - } - } else if (specWidthMode == MeasureSpec.EXACTLY || specWidthMode == MeasureSpec.AT_MOST) { - if (specHeightMode == MeasureSpec.EXACTLY) { - //Pick the smaller of the two explicit sizes - measureTileSize = Math.min(desiredTileWidth, desiredTileHeight); - } else { - //Be the width size the user wants - measureTileSize = desiredTileWidth; - } - } else if (specHeightMode == MeasureSpec.EXACTLY || specHeightMode == MeasureSpec.AT_MOST) { - //Be the height size the user wants - measureTileSize = desiredTileHeight; - } - - if (measureTileSize > 0) { - //Use measureTileSize if set - measureTileHeight = measureTileSize; - measureTileWidth = measureTileSize; - } else if (measureTileSize <= 0) { - if (measureTileWidth <= 0) { - //Set width to default if no value were set - measureTileWidth = dpToPx(DEFAULT_TILE_SIZE_DP); - } - if (measureTileHeight <= 0) { - //Set height to default if no value were set - measureTileHeight = dpToPx(DEFAULT_TILE_SIZE_DP); - } - } - - //Calculate our size based off our measured tile size - int measuredWidth = measureTileWidth * DEFAULT_DAYS_IN_WEEK; - int measuredHeight = measureTileHeight * viewTileHeight; - - //Put padding back in from when we took it away - measuredWidth += getPaddingLeft() + getPaddingRight(); - measuredHeight += getPaddingTop() + getPaddingBottom(); - - //Contract fulfilled, setting out measurements - setMeasuredDimension( - //We clamp inline because we want to use un-clamped versions on the children - clampSize(measuredWidth, widthMeasureSpec), - clampSize(measuredHeight, heightMeasureSpec) - ); - - int count = getChildCount(); - - for (int i = 0; i < count; i++) { - final View child = getChildAt(i); - - LayoutParams p = (LayoutParams) child.getLayoutParams(); - - int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec( - DEFAULT_DAYS_IN_WEEK * measureTileWidth, - MeasureSpec.EXACTLY - ); - - int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( - p.height * measureTileHeight, - MeasureSpec.EXACTLY - ); - - child.measure(childWidthMeasureSpec, childHeightMeasureSpec); - } - } - - private int getWeekCountBasedOnMode() { - int weekCount = calendarMode.visibleWeeksCount; - final boolean isInMonthsMode = calendarMode.equals(CalendarMode.MONTHS); - if (isInMonthsMode && mDynamicHeightEnabled && adapter != null && pager != null) { - final LocalDate cal = adapter.getItem(pager.getCurrentItem()).getDate(); - final LocalDate tempLastDay = cal.withDayOfMonth(cal.lengthOfMonth()); - weekCount = tempLastDay.get(WeekFields.of(firstDayOfWeek, 1).weekOfMonth()); - } - return showWeekDays ? weekCount + DAY_NAMES_ROW : weekCount; - } - - /** - * Clamp the size to the measure spec. - * - * @param size Size we want to be - * @param spec Measure spec to clamp against - * @return the appropriate size to pass to {@linkplain View#setMeasuredDimension(int, int)} - */ - private static int clampSize(int size, int spec) { - int specMode = MeasureSpec.getMode(spec); - int specSize = MeasureSpec.getSize(spec); - switch (specMode) { - case MeasureSpec.EXACTLY: { - return specSize; - } - case MeasureSpec.AT_MOST: { - return Math.min(size, specSize); - } - case MeasureSpec.UNSPECIFIED: - default: { - return size; - } - } - } - - /** - * {@inheritDoc} - */ - @Override - protected void onLayout(boolean changed, int left, int top, int right, int bottom) { - final int count = getChildCount(); - - final int parentLeft = getPaddingLeft(); - final int parentWidth = right - left - parentLeft - getPaddingRight(); - - int childTop = getPaddingTop(); - - for (int i = 0; i < count; i++) { - final View child = getChildAt(i); - if (child.getVisibility() == View.GONE) { - continue; - } - - final int width = child.getMeasuredWidth(); - final int height = child.getMeasuredHeight(); - - int delta = (parentWidth - width) / 2; - int childLeft = parentLeft + delta; - - child.layout(childLeft, childTop, childLeft + width, childTop + height); - - childTop += height; - } - } - - /** - * {@inheritDoc} - */ - @Override - public LayoutParams generateLayoutParams(AttributeSet attrs) { - return new LayoutParams(1); - } - - @Override - public boolean shouldDelayChildPressedState() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { - return p instanceof LayoutParams; - } - - @Override - protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { - return new LayoutParams(1); - } - - @Override - public void onInitializeAccessibilityEvent(@NonNull AccessibilityEvent event) { - super.onInitializeAccessibilityEvent(event); - event.setClassName(MaterialCalendarView.class.getName()); - } - - @Override - public void onInitializeAccessibilityNodeInfo(@NonNull AccessibilityNodeInfo info) { - super.onInitializeAccessibilityNodeInfo(info); - info.setClassName(MaterialCalendarView.class.getName()); - } - - /** - * Simple layout params for MaterialCalendarView. The only variation for layout is height. - */ - protected static class LayoutParams extends MarginLayoutParams { - - /** - * Create a layout that matches parent width, and is X number of tiles high + accentColor = color; + adapter.setSelectionColor(color); + invalidate(); + } + + /** + * Set content description for button past * - * @param tileHeight view height in number of tiles - */ - public LayoutParams(int tileHeight) { - super(MATCH_PARENT, tileHeight); - } - } - - /** - * Enable or disable the ability to swipe between months. - * - * @param pagingEnabled pass false to disable paging, true to enable (default) - */ - public void setPagingEnabled(boolean pagingEnabled) { - pager.setPagingEnabled(pagingEnabled); - updateUi(); - } - - /** - * @return true if swiping months is enabled, false if disabled. Default is true. - */ - public boolean isPagingEnabled() { - return pager.isPagingEnabled(); - } - - /** - * Preserve the current parameters of the Material Calendar View. - */ - public State state() { - return state; - } - - /** - * Initialize the parameters from scratch. - */ - public StateBuilder newState() { - return new StateBuilder(); - } - - public class State { - private final CalendarMode calendarMode; - private final DayOfWeek firstDayOfWeek; - private final CalendarDay minDate; - private final CalendarDay maxDate; - private final boolean cacheCurrentPosition; - private final boolean showWeekDays; - - private State(final StateBuilder builder) { - calendarMode = builder.calendarMode; - firstDayOfWeek = builder.firstDayOfWeek; - minDate = builder.minDate; - maxDate = builder.maxDate; - cacheCurrentPosition = builder.cacheCurrentPosition; - showWeekDays = builder.showWeekDays; - } - - /** - * Modify parameters from current state. - */ - public StateBuilder edit() { - return new StateBuilder(this); - } - } - - public class StateBuilder { - private CalendarMode calendarMode; - private DayOfWeek firstDayOfWeek; - private boolean cacheCurrentPosition = false; - private CalendarDay minDate = null; - private CalendarDay maxDate = null; - private boolean showWeekDays; + * @param description String to use as content description + */ + public void setContentDescriptionArrowPast(final CharSequence description) { + buttonPast.setContentDescription(description); + } + + /** + * Set content description for button future + * + * @param description String to use as content description + */ + public void setContentDescriptionArrowFuture(final CharSequence description) { + buttonFuture.setContentDescription(description); + } - public StateBuilder() { - calendarMode = CalendarMode.MONTHS; - firstDayOfWeek = - LocalDate.now().with(WeekFields.of(Locale.getDefault()).dayOfWeek(), 1).getDayOfWeek(); + /** + * Set content description for calendar + * + * @param description String to use as content description + */ + public void setContentDescriptionCalendar(final CharSequence description) { + calendarContentDescription = description; } - private StateBuilder(final State state) { - calendarMode = state.calendarMode; - firstDayOfWeek = state.firstDayOfWeek; - minDate = state.minDate; - maxDate = state.maxDate; - cacheCurrentPosition = state.cacheCurrentPosition; - showWeekDays = state.showWeekDays; + /** + * Get content description for calendar + * + * @return calendar's content description + */ + public CharSequence getCalendarContentDescription() { + return calendarContentDescription != null + ? calendarContentDescription + : getContext().getString(R.string.calendar); } /** - * Sets the first day of the week. - *

- * Uses the {@link DayOfWeek} day constants. + * Set a formatter for day content description. * - * @param day The first day of the week as a {@link DayOfWeek} enum. - * @see java.util.Calendar + * @param formatter the new formatter, null for default */ - public StateBuilder setFirstDayOfWeek(DayOfWeek day) { - this.firstDayOfWeek = day; - return this; + public void setDayFormatterContentDescription(DayFormatter formatter) { + adapter.setDayFormatterContentDescription(formatter); } /** - * Set calendar display mode. The default mode is Months. - * When switching between modes will select todays date, or the selected date, - * if selection mode is single. + * @return icon used for the left arrow + */ + public Drawable getLeftArrow() { + return buttonPast.getDrawable(); + } + + /** + * @param icon the new icon to use for the left paging arrow + */ + public void setLeftArrow(@DrawableRes final int icon) { + buttonPast.setImageResource(icon); + } + + /** + * @return icon used for the right arrow + */ + public Drawable getRightArrow() { + return buttonFuture.getDrawable(); + } + + /** + * @param icon the new icon to use for the right paging arrow + */ + public void setRightArrow(@DrawableRes final int icon) { + buttonFuture.setImageResource(icon); + } + + /** + * @param resourceId The text appearance resource id. + */ + public void setHeaderTextAppearance(int resourceId) { + title.setTextAppearance(getContext(), resourceId); + } + + /** + * @param resourceId The text appearance resource id. + */ + public void setDateTextAppearance(int resourceId) { + adapter.setDateTextAppearance(resourceId); + } + + /** + * @param resourceId The text appearance resource id. + */ + public void setWeekDayTextAppearance(int resourceId) { + adapter.setWeekDayTextAppearance(resourceId); + } + + /** + * Get the currently selected date, or null if no selection. Depending on the selection mode, + * you might get different results. + * + *

For {@link #SELECTION_MODE_SINGLE}, returns the selected date.

+ *

For {@link #SELECTION_MODE_MULTIPLE}, returns the last date selected.

+ *

For {@link #SELECTION_MODE_RANGE}, returns the last date of the range. In most cases, you + * should probably be using {@link #getSelectedDates()}.

+ *

For {@link #SELECTION_MODE_NONE}, returns null.

+ * + * @return The selected day, or null if no selection. If in multiple selection mode, this + * will return the last date of the list of selected dates. + * @see MaterialCalendarView#getSelectedDates() + */ + @Nullable + public CalendarDay getSelectedDate() { + List dates = adapter.getSelectedDates(); + if (dates.isEmpty()) { + return null; + } else { + return dates.get(dates.size() - 1); + } + } + + /** + * Return the list of currently selected dates. Mostly useful for {@link #SELECTION_MODE_MULTIPLE} + * and {@link #SELECTION_MODE_RANGE}. For the other modes, check {@link #getSelectedDate()}. * - * @param mode - calendar mode + *

For {@link #SELECTION_MODE_MULTIPLE}, returns the list in the order of selection.

+ *

For {@link #SELECTION_MODE_RANGE}, returns the range of dates ordered chronologically.

+ * + * @return All of the currently selected dates. + * @see MaterialCalendarView#getSelectedDate() + */ + @NonNull + public List getSelectedDates() { + return adapter.getSelectedDates(); + } + + /** + * Clear the currently selected date(s) + */ + public void clearSelection() { + List dates = getSelectedDates(); + adapter.clearSelections(); + for (CalendarDay day : dates) { + dispatchOnDateSelected(day, false); + } + } + + /** + * @param date a Date set to a day to select. Null to clear selection */ - public StateBuilder setCalendarDisplayMode(CalendarMode mode) { - this.calendarMode = mode; - return this; + public void setSelectedDate(@Nullable LocalDate date) { + setSelectedDate(CalendarDay.from(date)); } /** - * @param date set the minimum selectable date, null for no minimum + * @param date a Date to set as selected. Null to clear selection */ - public StateBuilder setMinimumDate(@Nullable LocalDate date) { - setMinimumDate(CalendarDay.from(date)); - return this; + public void setSelectedDate(@Nullable CalendarDay date) { + clearSelection(); + if (date != null) { + setDateSelected(date, true); + } } /** - * @param calendar set the minimum selectable date, null for no minimum + * @param day a CalendarDay to change. Passing null does nothing + * @param selected true if day should be selected, false to deselect */ - public StateBuilder setMinimumDate(@Nullable CalendarDay calendar) { - minDate = calendar; - return this; + public void setDateSelected(@Nullable CalendarDay day, boolean selected) { + if (day == null) { + return; + } + adapter.setDateSelected(day, selected); } /** - * @param date set the maximum selectable date, null for no maximum + * Get the current first day of the month in month mode, or the first visible day of the + * currently visible week. + *

+ * For example, in week mode, if the week is July 29th, 2018 to August 4th, 2018, + * this will return July 29th, 2018. If in month mode and the month is august, then this method + * will return August 1st, 2018. + * + * @return The current month or week shown, will be set to first day of the month in month mode, + * or the first visible day for a week. */ - public StateBuilder setMaximumDate(@Nullable LocalDate date) { - setMaximumDate(CalendarDay.from(date)); - return this; + public CalendarDay getCurrentDate() { + return adapter.getItem(pager.getCurrentItem()); } /** - * @param calendar set the maximum selectable date, null for no maximum + * Set the calendar to a specific month or week based on a date. + *

+ * In month mode, the calendar will be set to the corresponding month. + *

+ * In week mode, the calendar will be set to the corresponding week. + * + * @param calendar a Calendar set to a day to focus the calendar on. Null will do nothing */ - public StateBuilder setMaximumDate(@Nullable CalendarDay calendar) { - maxDate = calendar; - return this; + public void setCurrentDate(@Nullable LocalDate calendar) { + setCurrentDate(CalendarDay.from(calendar)); } /** - * @param showWeekDays true to show week days names + * Set the calendar to a specific month or week based on a date. + *

+ * In month mode, the calendar will be set to the corresponding month. + *

+ * In week mode, the calendar will be set to the corresponding week. + * + * @param day a CalendarDay to focus the calendar on. Null will do nothing */ - public StateBuilder setShowWeekDays(boolean showWeekDays) { - this.showWeekDays = showWeekDays; - return this; + public void setCurrentDate(@Nullable CalendarDay day) { + setCurrentDate(day, true); } /** - * Use this method to enable saving the current position when switching - * between week and month mode. By default, the calendar update to the latest selected date - * or the current date. When set to true, the view will used the month that the calendar is - * currently on. + * Set the calendar to a specific month or week based on a date. + *

+ * In month mode, the calendar will be set to the corresponding month. + *

+ * In week mode, the calendar will be set to the corresponding week. * - * @param cacheCurrentPosition Set to true to cache the current position, false otherwise. - */ - public StateBuilder isCacheCalendarPositionEnabled(final boolean cacheCurrentPosition) { - this.cacheCurrentPosition = cacheCurrentPosition; - return this; - } - - public void commit() { - MaterialCalendarView.this.commit(new State(this)); - } - } - - private void commit(State state) { - // Use the calendarDayToShow to determine which date to focus on for the case of switching between month and week views - CalendarDay calendarDayToShow = null; - if (adapter != null && state.cacheCurrentPosition) { - calendarDayToShow = adapter.getItem(pager.getCurrentItem()); - if (calendarMode != state.calendarMode) { - CalendarDay currentlySelectedDate = getSelectedDate(); - if (calendarMode == CalendarMode.MONTHS && currentlySelectedDate != null) { - // Going from months to weeks - LocalDate lastVisibleCalendar = calendarDayToShow.getDate(); - CalendarDay lastVisibleCalendarDay = CalendarDay.from(lastVisibleCalendar.plusDays(1)); - if (currentlySelectedDate.equals(calendarDayToShow) || - (currentlySelectedDate.isAfter(calendarDayToShow) && currentlySelectedDate.isBefore( - lastVisibleCalendarDay))) { - // Currently selected date is within view, so center on that - calendarDayToShow = currentlySelectedDate; - } - } else if (calendarMode == CalendarMode.WEEKS) { - // Going from weeks to months - LocalDate lastVisibleCalendar = calendarDayToShow.getDate(); - CalendarDay lastVisibleCalendarDay = CalendarDay.from(lastVisibleCalendar.plusDays(6)); - if (currentlySelectedDate != null && - (currentlySelectedDate.equals(calendarDayToShow) || currentlySelectedDate.equals( - lastVisibleCalendarDay) || - (currentlySelectedDate.isAfter(calendarDayToShow) - && currentlySelectedDate.isBefore(lastVisibleCalendarDay)))) { - // Currently selected date is within view, so center on that - calendarDayToShow = currentlySelectedDate; - } else { - calendarDayToShow = lastVisibleCalendarDay; - } + * @param day a CalendarDay to focus the calendar on. Null will do nothing + * @param useSmoothScroll use smooth scroll when changing months. + */ + public void setCurrentDate(@Nullable CalendarDay day, boolean useSmoothScroll) { + if (day == null) { + return; } - } - } - - this.state = state; - // Save states parameters - calendarMode = state.calendarMode; - firstDayOfWeek = state.firstDayOfWeek; - minDate = state.minDate; - maxDate = state.maxDate; - showWeekDays = state.showWeekDays; - - // Recreate adapter - final CalendarPagerAdapter newAdapter; - switch (calendarMode) { - case MONTHS: - newAdapter = new MonthPagerAdapter(this); - break; - case WEEKS: - newAdapter = new WeekPagerAdapter(this); - break; - default: - throw new IllegalArgumentException("Provided display mode which is not yet implemented"); - } - if (adapter == null) { - adapter = newAdapter; - } else { - adapter = adapter.migrateStateAndReturn(newAdapter); - } - adapter.setShowWeekDays(showWeekDays); - pager.setAdapter(adapter); - setRangeDates(minDate, maxDate); - - // Reset height params after mode change - int tileHeight = showWeekDays ? calendarMode.visibleWeeksCount + DAY_NAMES_ROW - : calendarMode.visibleWeeksCount; - pager.setLayoutParams(new LayoutParams(tileHeight)); - - setCurrentDate( - selectionMode == SELECTION_MODE_SINGLE && !adapter.getSelectedDates().isEmpty() - ? adapter.getSelectedDates().get(0) - : CalendarDay.today()); - - if (calendarDayToShow != null) { - pager.setCurrentItem(adapter.getIndexForDay(calendarDayToShow)); - } - - invalidateDecorators(); - updateUi(); - } - - /** - * Used for enabling or disabling views, while also changing the alpha. - * - * @param view The view to enable or disable. - * @param enable Whether to enable or disable the view. - */ - private static void enableView(final View view, final boolean enable) { - view.setEnabled(enable); - view.setAlpha(enable ? 1f : 0.1f); - } + int index = adapter.getIndexForDay(day); + pager.setCurrentItem(index, useSmoothScroll); + updateUi(); + } + + /** + * @return the minimum selectable date for the calendar, if any + */ + public CalendarDay getMinimumDate() { + return minDate; + } + + /** + * @return the maximum selectable date for the calendar, if any + */ + public CalendarDay getMaximumDate() { + return maxDate; + } + + /** + * The default value is {@link #SHOW_DEFAULTS}, which currently is just {@link + * #SHOW_DECORATED_DISABLED}. + * This means that the default visible days are of the current month, in the min-max range. + * + * @param showOtherDates flags for showing non-enabled dates + * @see #SHOW_ALL + * @see #SHOW_NONE + * @see #SHOW_DEFAULTS + * @see #SHOW_OTHER_MONTHS + * @see #SHOW_OUT_OF_RANGE + * @see #SHOW_DECORATED_DISABLED + */ + public void setShowOtherDates(@ShowOtherDates int showOtherDates) { + adapter.setShowOtherDates(showOtherDates); + } + + /** + * Allow the user to click on dates from other months that are not out of range. Go to next or + * previous month if a day outside the current month is clicked. The day still need to be + * enabled to be selected. + * Default value is true. Should be used with {@link #SHOW_OTHER_MONTHS}. + * + * @param enabled True to allow the user to click on a day outside current month displayed + */ + public void setAllowClickDaysOutsideCurrentMonth(final boolean enabled) { + this.allowClickDaysOutsideCurrentMonth = enabled; + } + + /** + * Set a formatter for weekday labels. + * + * @param formatter the new formatter, null for default + */ + public void setWeekDayFormatter(WeekDayFormatter formatter) { + adapter.setWeekDayFormatter(formatter == null ? WeekDayFormatter.DEFAULT : formatter); + } + + /** + * Set a formatter for day labels. + * + * @param formatter the new formatter, null for default + */ + public void setDayFormatter(DayFormatter formatter) { + adapter.setDayFormatter(formatter == null ? DayFormatter.DEFAULT : formatter); + } + + /** + * Set a {@linkplain com.prolificinteractive.materialcalendarview.format.WeekDayFormatter} + * with the provided week day labels + * + * @param weekDayLabels Labels to use for the days of the week + * @see com.prolificinteractive.materialcalendarview.format.ArrayWeekDayFormatter + * @see #setWeekDayFormatter(com.prolificinteractive.materialcalendarview.format.WeekDayFormatter) + */ + public void setWeekDayLabels(CharSequence[] weekDayLabels) { + setWeekDayFormatter(new ArrayWeekDayFormatter(weekDayLabels)); + } + + /** + * Set a {@linkplain com.prolificinteractive.materialcalendarview.format.WeekDayFormatter} + * with the provided week day labels + * + * @param arrayRes String array resource of week day labels + * @see com.prolificinteractive.materialcalendarview.format.ArrayWeekDayFormatter + * @see #setWeekDayFormatter(com.prolificinteractive.materialcalendarview.format.WeekDayFormatter) + */ + public void setWeekDayLabels(@ArrayRes int arrayRes) { + setWeekDayLabels(getResources().getTextArray(arrayRes)); + } + + /** + * @return int of flags used for showing non-enabled dates + * @see #SHOW_ALL + * @see #SHOW_NONE + * @see #SHOW_DEFAULTS + * @see #SHOW_OTHER_MONTHS + * @see #SHOW_OUT_OF_RANGE + * @see #SHOW_DECORATED_DISABLED + */ + @ShowOtherDates + public int getShowOtherDates() { + return adapter.getShowOtherDates(); + } + + /** + * @return true if allow click on days outside current month displayed + */ + public boolean allowClickDaysOutsideCurrentMonth() { + return allowClickDaysOutsideCurrentMonth; + } + + /** + * @return true if the week days names are shown + */ + public boolean isShowWeekDays() { + return showWeekDays; + } + + /** + * Set a custom formatter for the month/year title + * + * @param titleFormatter new formatter to use, null to use default formatter + */ + public void setTitleFormatter(@Nullable TitleFormatter titleFormatter) { + titleChanger.setTitleFormatter(titleFormatter); + adapter.setTitleFormatter(titleFormatter); + updateUi(); + } + + /** + * Set a {@linkplain com.prolificinteractive.materialcalendarview.format.TitleFormatter} + * using the provided month labels + * + * @param monthLabels month labels to use + * @see com.prolificinteractive.materialcalendarview.format.MonthArrayTitleFormatter + * @see #setTitleFormatter(com.prolificinteractive.materialcalendarview.format.TitleFormatter) + */ + public void setTitleMonths(CharSequence[] monthLabels) { + setTitleFormatter(new MonthArrayTitleFormatter(monthLabels)); + } + + /** + * Set a {@linkplain com.prolificinteractive.materialcalendarview.format.TitleFormatter} + * using the provided month labels + * + * @param arrayRes String array resource of month labels to use + * @see com.prolificinteractive.materialcalendarview.format.MonthArrayTitleFormatter + * @see #setTitleFormatter(com.prolificinteractive.materialcalendarview.format.TitleFormatter) + */ + public void setTitleMonths(@ArrayRes int arrayRes) { + setTitleMonths(getResources().getTextArray(arrayRes)); + } + + /** + * Change the title animation orientation to have a different look and feel. + * + * @param orientation {@link MaterialCalendarView#VERTICAL} or {@link + * MaterialCalendarView#HORIZONTAL} + */ + public void setTitleAnimationOrientation(final int orientation) { + titleChanger.setOrientation(orientation); + } + + /** + * Get the orientation of the animation of the title. + * + * @return Title animation orientation {@link MaterialCalendarView#VERTICAL} or {@link + * MaterialCalendarView#HORIZONTAL} + */ + public int getTitleAnimationOrientation() { + return titleChanger.getOrientation(); + } + + /** + * Sets the visibility {@link #topbar}, which contains + * the previous month button {@link #buttonPast}, next month button {@link #buttonFuture}, + * and the month title {@link #title}. + * + * @param visible Boolean indicating if the topbar is visible + */ + public void setTopbarVisible(boolean visible) { + topbar.setVisibility(visible ? View.VISIBLE : View.GONE); + requestLayout(); + } + + /** + * @return true if the topbar is visible + */ + public boolean getTopbarVisible() { + return topbar.getVisibility() == View.VISIBLE; + } + + /** + * Get the current {@link CalendarMode} set of the Calendar. + * + * @return Whichever mode the calendar is currently in. + */ + public CalendarMode getCalendarMode() { + return calendarMode; + } + + @Override + protected Parcelable onSaveInstanceState() { + SavedState ss = new SavedState(super.onSaveInstanceState()); + ss.showOtherDates = getShowOtherDates(); + ss.allowClickDaysOutsideCurrentMonth = allowClickDaysOutsideCurrentMonth(); + ss.minDate = getMinimumDate(); + ss.maxDate = getMaximumDate(); + ss.selectedDates = getSelectedDates(); + ss.selectionMode = getSelectionMode(); + ss.topbarVisible = getTopbarVisible(); + ss.dynamicHeightEnabled = mDynamicHeightEnabled; + ss.currentMonth = currentMonth; + ss.cacheCurrentPosition = state.cacheCurrentPosition; + return ss; + } + + @Override + protected void onRestoreInstanceState(Parcelable state) { + SavedState ss = (SavedState) state; + super.onRestoreInstanceState(ss.getSuperState()); + state().edit() + .setMinimumDate(ss.minDate) + .setMaximumDate(ss.maxDate) + .isCacheCalendarPositionEnabled(ss.cacheCurrentPosition) + .commit(); + + setShowOtherDates(ss.showOtherDates); + setAllowClickDaysOutsideCurrentMonth(ss.allowClickDaysOutsideCurrentMonth); + clearSelection(); + for (CalendarDay calendarDay : ss.selectedDates) { + setDateSelected(calendarDay, true); + } + setTopbarVisible(ss.topbarVisible); + setSelectionMode(ss.selectionMode); + setDynamicHeightEnabled(ss.dynamicHeightEnabled); + setCurrentDate(ss.currentMonth); + } + + @Override + protected void dispatchSaveInstanceState(@NonNull SparseArray container) { + dispatchFreezeSelfOnly(container); + } + + @Override + protected void dispatchRestoreInstanceState(@NonNull SparseArray container) { + dispatchThawSelfOnly(container); + } + + private void setRangeDates(CalendarDay min, CalendarDay max) { + CalendarDay c = currentMonth; + adapter.setRangeDates(min, max); + currentMonth = c; + if (min != null) { + currentMonth = min.isAfter(currentMonth) ? min : currentMonth; + } + int position = adapter.getIndexForDay(c); + pager.setCurrentItem(position, false); + updateUi(); + } + + public static class SavedState extends BaseSavedState { + + int showOtherDates = SHOW_DEFAULTS; + boolean allowClickDaysOutsideCurrentMonth = true; + CalendarDay minDate = null; + CalendarDay maxDate = null; + List selectedDates = new ArrayList<>(); + boolean topbarVisible = true; + int selectionMode = SELECTION_MODE_SINGLE; + boolean dynamicHeightEnabled = false; + CalendarDay currentMonth = null; + boolean cacheCurrentPosition; + + SavedState(Parcelable superState) { + super(superState); + } + + @Override + public void writeToParcel(@NonNull Parcel out, int flags) { + super.writeToParcel(out, flags); + out.writeInt(showOtherDates); + out.writeByte((byte) (allowClickDaysOutsideCurrentMonth ? 1 : 0)); + out.writeParcelable(minDate, 0); + out.writeParcelable(maxDate, 0); + out.writeTypedList(selectedDates); + out.writeInt(topbarVisible ? 1 : 0); + out.writeInt(selectionMode); + out.writeInt(dynamicHeightEnabled ? 1 : 0); + out.writeParcelable(currentMonth, 0); + out.writeByte((byte) (cacheCurrentPosition ? 1 : 0)); + } + + public static final Parcelable.Creator CREATOR + = new Parcelable.Creator() { + public SavedState createFromParcel(Parcel in) { + return new SavedState(in); + } + + public SavedState[] newArray(int size) { + return new SavedState[size]; + } + }; + + private SavedState(Parcel in) { + super(in); + showOtherDates = in.readInt(); + allowClickDaysOutsideCurrentMonth = in.readByte() != 0; + ClassLoader loader = CalendarDay.class.getClassLoader(); + minDate = in.readParcelable(loader); + maxDate = in.readParcelable(loader); + in.readTypedList(selectedDates, CalendarDay.getCREATOR()); + topbarVisible = in.readInt() == 1; + selectionMode = in.readInt(); + dynamicHeightEnabled = in.readInt() == 1; + currentMonth = in.readParcelable(loader); + cacheCurrentPosition = in.readByte() != 0; + } + } + + private static int getThemeAccentColor(Context context) { + int colorAttr; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + colorAttr = android.R.attr.colorAccent; + } else { + //Get colorAccent defined for AppCompat + colorAttr = + context.getResources().getIdentifier("colorAccent", "attr", context.getPackageName()); + } + TypedValue outValue = new TypedValue(); + context.getTheme().resolveAttribute(colorAttr, outValue, true); + return outValue.data; + } + + /** + * @return The first day of the week as a {@linkplain Calendar} day constant. + */ + public DayOfWeek getFirstDayOfWeek() { + return firstDayOfWeek; + } + + /** + * By default, the calendar will take up all the space needed to show any month (6 rows). + * By enabling dynamic height, the view will change height dependant on the visible month. + *

+ * This means months that only need 5 or 4 rows to show the entire month will only take up + * that many rows, and will grow and shrink as necessary. + * + * @param useDynamicHeight true to have the view different heights based on the visible month + */ + public void setDynamicHeightEnabled(boolean useDynamicHeight) { + this.mDynamicHeightEnabled = useDynamicHeight; + } + + /** + * @return the dynamic height state - true if enabled. + */ + public boolean isDynamicHeightEnabled() { + return mDynamicHeightEnabled; + } + + /** + * Add a collection of day decorators + * + * @param decorators decorators to add + */ + public void addDecorators(Collection decorators) { + if (decorators == null) { + return; + } + + dayViewDecorators.addAll(decorators); + adapter.setDecorators(dayViewDecorators); + } + + /** + * Add several day decorators + * + * @param decorators decorators to add + */ + public void addDecorators(DayViewDecorator... decorators) { + addDecorators(Arrays.asList(decorators)); + } + + /** + * Add a day decorator + * + * @param decorator decorator to add + */ + public void addDecorator(DayViewDecorator decorator) { + if (decorator == null) { + return; + } + dayViewDecorators.add(decorator); + adapter.setDecorators(dayViewDecorators); + } + + /** + * Remove all decorators + */ + public void removeDecorators() { + dayViewDecorators.clear(); + adapter.setDecorators(dayViewDecorators); + } + + /** + * Remove a specific decorator instance. Same rules as {@linkplain List#remove(Object)} + * + * @param decorator decorator to remove + */ + public void removeDecorator(DayViewDecorator decorator) { + dayViewDecorators.remove(decorator); + adapter.setDecorators(dayViewDecorators); + } + + /** + * Invalidate decorators after one has changed internally. That is, if a decorator mutates, you + * should call this method to update the widget. + */ + public void invalidateDecorators() { + adapter.invalidateDecorators(); + } + + /* + * Listener/Callback Code + */ + + /** + * Sets the listener to be notified upon selected date changes. + * + * @param listener thing to be notified + */ + public void setOnDateChangedListener(OnDateSelectedListener listener) { + this.listener = listener; + } + + /** + * Sets the listener to be notified upon long clicks on dates. + * + * @param longClickListener thing to be notified + */ + public void setOnDateLongClickListener(OnDateLongClickListener longClickListener) { + this.longClickListener = longClickListener; + } + + /** + * Sets the listener to be notified upon month changes. + * + * @param listener thing to be notified + */ + public void setOnMonthChangedListener(OnMonthChangedListener listener) { + this.monthListener = listener; + } + + /** + * Sets the listener to be notified upon a range has been selected. + * + * @param listener thing to be notified + */ + public void setOnRangeSelectedListener(OnRangeSelectedListener listener) { + this.rangeListener = listener; + } + + /** + * Add listener to the title or null to remove it. + * + * @param listener Listener to be notified. + */ + public void setOnTitleClickListener(final OnClickListener listener) { + title.setOnClickListener(listener); + } + + /** + * Dispatch date change events to a listener, if set + * + * @param day the day that was selected + * @param selected true if the day is now currently selected, false otherwise + */ + protected void dispatchOnDateSelected(final CalendarDay day, final boolean selected) { + if (listener != null) { + listener.onDateSelected(MaterialCalendarView.this, day, selected); + } + } + + /** + * Dispatch a range of days to a range listener, if set, ordered chronologically. + * + * @param days Enclosing days ordered from first to last day. + */ + protected void dispatchOnRangeSelected(@NonNull final List days) { + if (rangeListener != null) { + rangeListener.onRangeSelected(MaterialCalendarView.this, days); + } + } + + /** + * Dispatch date change events to a listener, if set + * + * @param day first day of the new month + */ + protected void dispatchOnMonthChanged(final CalendarDay day) { + if (monthListener != null) { + monthListener.onMonthChanged(MaterialCalendarView.this, day); + } + } + + /** + * Call by {@link CalendarPagerView} to indicate that a day was clicked and we should handle it. + * This method will always process the click to the selected date. + * + * @param date date of the day that was clicked + * @param nowSelected true if the date is now selected, false otherwise + */ + protected void onDateClicked(@NonNull CalendarDay date, boolean nowSelected) { + switch (selectionMode) { + case SELECTION_MODE_MULTIPLE: { + adapter.setDateSelected(date, nowSelected); + dispatchOnDateSelected(date, nowSelected); + } + break; + case SELECTION_MODE_RANGE: { + final List currentSelection = adapter.getSelectedDates(); + + if (currentSelection.size() == 0) { + // Selecting the first date of a range + adapter.setDateSelected(date, nowSelected); + dispatchOnDateSelected(date, nowSelected); + } else if (currentSelection.size() == 1) { + // Selecting the second date of a range + final CalendarDay firstDaySelected = currentSelection.get(0); + if (firstDaySelected.equals(date)) { + // Right now, we are not supporting a range of one day, so we are removing the day instead. + adapter.setDateSelected(date, nowSelected); + dispatchOnDateSelected(date, nowSelected); + } else if (firstDaySelected.isAfter(date)) { + // Selecting a range, dispatching in reverse order... + adapter.selectRange(date, firstDaySelected); + dispatchOnRangeSelected(adapter.getSelectedDates()); + } else { + // Selecting a range, dispatching in order... + adapter.selectRange(firstDaySelected, date); + dispatchOnRangeSelected(adapter.getSelectedDates()); + } + } else { + // Clearing selection and making a selection of the new date. + adapter.clearSelections(); + adapter.setDateSelected(date, nowSelected); + dispatchOnDateSelected(date, nowSelected); + } + } + break; + default: + case SELECTION_MODE_SINGLE: { + adapter.clearSelections(); + adapter.setDateSelected(date, true); + dispatchOnDateSelected(date, true); + } + break; + } + } + + /** + * Select a fresh range of date including first day and last day. + * + * @param firstDay first day of the range to select + * @param lastDay last day of the range to select + */ + public void selectRange(final CalendarDay firstDay, final CalendarDay lastDay) { + if (firstDay == null || lastDay == null) { + return; + } else if (firstDay.isAfter(lastDay)) { + adapter.selectRange(lastDay, firstDay); + dispatchOnRangeSelected(adapter.getSelectedDates()); + } else { + adapter.selectRange(firstDay, lastDay); + dispatchOnRangeSelected(adapter.getSelectedDates()); + } + } + + /** + * Call by {@link CalendarPagerView} to indicate that a day was clicked and we should handle it + */ + protected void onDateClicked(final DayView dayView) { + final CalendarDay currentDate = getCurrentDate(); + final CalendarDay selectedDate = dayView.getDate(); + final int currentMonth = currentDate.getMonth(); + final int selectedMonth = selectedDate.getMonth(); + + if (calendarMode == CalendarMode.MONTHS + && allowClickDaysOutsideCurrentMonth + && currentMonth != selectedMonth) { + if (currentDate.isAfter(selectedDate)) { + goToPrevious(); + } else if (currentDate.isBefore(selectedDate)) { + goToNext(); + } + } + onDateClicked(dayView.getDate(), !dayView.isChecked()); + } + + /** + * Call by {@link CalendarPagerView} to indicate that a day was long clicked and we should handle + * it + */ + protected void onDateLongClicked(final DayView dayView) { + if (longClickListener != null) { + longClickListener.onDateLongClick(MaterialCalendarView.this, dayView.getDate()); + } + } + + /** + * Called by the adapter for cases when changes in state result in dates being unselected + * + * @param date date that should be de-selected + */ + protected void onDateUnselected(CalendarDay date) { + dispatchOnDateSelected(date, false); + } + + /* + * Show Other Dates Utils + */ + + /** + * @param showOtherDates int flag for show other dates + * @return true if the other months flag is set + */ + public static boolean showOtherMonths(@ShowOtherDates int showOtherDates) { + return (showOtherDates & SHOW_OTHER_MONTHS) != 0; + } + + /** + * @param showOtherDates int flag for show other dates + * @return true if the out of range flag is set + */ + public static boolean showOutOfRange(@ShowOtherDates int showOtherDates) { + return (showOtherDates & SHOW_OUT_OF_RANGE) != 0; + } + + /** + * @param showOtherDates int flag for show other dates + * @return true if the decorated disabled flag is set + */ + public static boolean showDecoratedDisabled(@ShowOtherDates int showOtherDates) { + return (showOtherDates & SHOW_DECORATED_DISABLED) != 0; + } + + /* + * Custom ViewGroup Code + */ + + /** + * {@inheritDoc} + */ + @Override + protected LayoutParams generateDefaultLayoutParams() { + return new LayoutParams(1); + } + + /** + * {@inheritDoc} + */ + @Override + protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { + final int specWidthSize = MeasureSpec.getSize(widthMeasureSpec); + final int specWidthMode = MeasureSpec.getMode(widthMeasureSpec); + final int specHeightSize = MeasureSpec.getSize(heightMeasureSpec); + final int specHeightMode = MeasureSpec.getMode(heightMeasureSpec); + + //We need to disregard padding for a while. This will be added back later + final int desiredWidth = specWidthSize - getPaddingLeft() - getPaddingRight(); + final int desiredHeight = specHeightSize - getPaddingTop() - getPaddingBottom(); + + final int weekCount = getWeekCountBasedOnMode(); + + final int viewTileHeight = getTopbarVisible() ? (weekCount + 1) : weekCount; + + //Calculate independent tile sizes for later + int desiredTileWidth = desiredWidth / DEFAULT_DAYS_IN_WEEK; + int desiredTileHeight = desiredHeight / viewTileHeight; + + int measureTileSize = -1; + int measureTileWidth = -1; + int measureTileHeight = -1; + + if (this.tileWidth != INVALID_TILE_DIMENSION || this.tileHeight != INVALID_TILE_DIMENSION) { + if (this.tileWidth > 0) { + //We have a tileWidth set, we should use that + measureTileWidth = this.tileWidth; + } else { + measureTileWidth = desiredTileWidth; + } + if (this.tileHeight > 0) { + //We have a tileHeight set, we should use that + measureTileHeight = this.tileHeight; + } else { + measureTileHeight = desiredTileHeight; + } + } else if (specWidthMode == MeasureSpec.EXACTLY || specWidthMode == MeasureSpec.AT_MOST) { + if (specHeightMode == MeasureSpec.EXACTLY) { + //Pick the smaller of the two explicit sizes + measureTileSize = Math.min(desiredTileWidth, desiredTileHeight); + } else { + //Be the width size the user wants + measureTileSize = desiredTileWidth; + } + } else if (specHeightMode == MeasureSpec.EXACTLY || specHeightMode == MeasureSpec.AT_MOST) { + //Be the height size the user wants + measureTileSize = desiredTileHeight; + } + + if (measureTileSize > 0) { + //Use measureTileSize if set + measureTileHeight = measureTileSize; + measureTileWidth = measureTileSize; + } else if (measureTileSize <= 0) { + if (measureTileWidth <= 0) { + //Set width to default if no value were set + measureTileWidth = dpToPx(DEFAULT_TILE_SIZE_DP); + } + if (measureTileHeight <= 0) { + //Set height to default if no value were set + measureTileHeight = dpToPx(DEFAULT_TILE_SIZE_DP); + } + } + + //Calculate our size based off our measured tile size + int measuredWidth = measureTileWidth * DEFAULT_DAYS_IN_WEEK; + int measuredHeight = measureTileHeight * viewTileHeight; + + //Put padding back in from when we took it away + measuredWidth += getPaddingLeft() + getPaddingRight(); + measuredHeight += getPaddingTop() + getPaddingBottom(); + + //Contract fulfilled, setting out measurements + setMeasuredDimension( + //We clamp inline because we want to use un-clamped versions on the children + clampSize(measuredWidth, widthMeasureSpec), + clampSize(measuredHeight, heightMeasureSpec) + ); + + int count = getChildCount(); + + for (int i = 0; i < count; i++) { + final View child = getChildAt(i); + + LayoutParams p = (LayoutParams) child.getLayoutParams(); + + int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec( + DEFAULT_DAYS_IN_WEEK * measureTileWidth, + MeasureSpec.EXACTLY + ); + + int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( + p.height * measureTileHeight, + MeasureSpec.EXACTLY + ); + + child.measure(childWidthMeasureSpec, childHeightMeasureSpec); + } + } + + private int getWeekCountBasedOnMode() { + int weekCount = calendarMode.getVisibleWeeksCount(); + final boolean isInMonthsMode = calendarMode.equals(CalendarMode.MONTHS); + if (isInMonthsMode && mDynamicHeightEnabled && adapter != null && pager != null) { + final LocalDate cal = adapter.getItem(pager.getCurrentItem()).getDate(); + final LocalDate tempLastDay = cal.withDayOfMonth(cal.lengthOfMonth()); + weekCount = tempLastDay.get(WeekFields.of(firstDayOfWeek, 1).weekOfMonth()); + } + return showWeekDays ? weekCount + DAY_NAMES_ROW : weekCount; + } + + /** + * Clamp the size to the measure spec. + * + * @param size Size we want to be + * @param spec Measure spec to clamp against + * @return the appropriate size to pass to {@linkplain View#setMeasuredDimension(int, int)} + */ + private static int clampSize(int size, int spec) { + int specMode = MeasureSpec.getMode(spec); + int specSize = MeasureSpec.getSize(spec); + switch (specMode) { + case MeasureSpec.EXACTLY: { + return specSize; + } + case MeasureSpec.AT_MOST: { + return Math.min(size, specSize); + } + case MeasureSpec.UNSPECIFIED: + default: { + return size; + } + } + } + + /** + * {@inheritDoc} + */ + @Override + protected void onLayout(boolean changed, int left, int top, int right, int bottom) { + final int count = getChildCount(); + + final int parentLeft = getPaddingLeft(); + final int parentWidth = right - left - parentLeft - getPaddingRight(); + + int childTop = getPaddingTop(); + + for (int i = 0; i < count; i++) { + final View child = getChildAt(i); + if (child.getVisibility() == View.GONE) { + continue; + } + + final int width = child.getMeasuredWidth(); + final int height = child.getMeasuredHeight(); + + int delta = (parentWidth - width) / 2; + int childLeft = parentLeft + delta; + + child.layout(childLeft, childTop, childLeft + width, childTop + height); + + childTop += height; + } + } + + /** + * {@inheritDoc} + */ + @Override + public LayoutParams generateLayoutParams(AttributeSet attrs) { + return new LayoutParams(1); + } + + @Override + public boolean shouldDelayChildPressedState() { + return false; + } + + /** + * {@inheritDoc} + */ + @Override + protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { + return p instanceof LayoutParams; + } + + @Override + protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { + return new LayoutParams(1); + } + + @Override + public void onInitializeAccessibilityEvent(@NonNull AccessibilityEvent event) { + super.onInitializeAccessibilityEvent(event); + event.setClassName(MaterialCalendarView.class.getName()); + } + + @Override + public void onInitializeAccessibilityNodeInfo(@NonNull AccessibilityNodeInfo info) { + super.onInitializeAccessibilityNodeInfo(info); + info.setClassName(MaterialCalendarView.class.getName()); + } + + /** + * Simple layout params for MaterialCalendarView. The only variation for layout is height. + */ + protected static class LayoutParams extends MarginLayoutParams { + + /** + * Create a layout that matches parent width, and is X number of tiles high + * + * @param tileHeight view height in number of tiles + */ + public LayoutParams(int tileHeight) { + super(MATCH_PARENT, tileHeight); + } + } + + /** + * Enable or disable the ability to swipe between months. + * + * @param pagingEnabled pass false to disable paging, true to enable (default) + */ + public void setPagingEnabled(boolean pagingEnabled) { + pager.setPagingEnabled(pagingEnabled); + updateUi(); + } + + /** + * @return true if swiping months is enabled, false if disabled. Default is true. + */ + public boolean isPagingEnabled() { + return pager.isPagingEnabled(); + } + + /** + * Preserve the current parameters of the Material Calendar View. + */ + public State state() { + return state; + } + + /** + * Initialize the parameters from scratch. + */ + public StateBuilder newState() { + return new StateBuilder(); + } + + public class State { + private final CalendarMode calendarMode; + private final DayOfWeek firstDayOfWeek; + private final CalendarDay minDate; + private final CalendarDay maxDate; + private final boolean cacheCurrentPosition; + private final boolean showWeekDays; + + private State(final StateBuilder builder) { + calendarMode = builder.calendarMode; + firstDayOfWeek = builder.firstDayOfWeek; + minDate = builder.minDate; + maxDate = builder.maxDate; + cacheCurrentPosition = builder.cacheCurrentPosition; + showWeekDays = builder.showWeekDays; + } + + /** + * Modify parameters from current state. + */ + public StateBuilder edit() { + return new StateBuilder(this); + } + } + + public class StateBuilder { + private CalendarMode calendarMode; + private DayOfWeek firstDayOfWeek; + private boolean cacheCurrentPosition = false; + private CalendarDay minDate = null; + private CalendarDay maxDate = null; + private boolean showWeekDays; + + public StateBuilder() { + calendarMode = CalendarMode.MONTHS; + firstDayOfWeek = + LocalDate.now().with(WeekFields.of(Locale.getDefault()).dayOfWeek(), 1).getDayOfWeek(); + } + + private StateBuilder(final State state) { + calendarMode = state.calendarMode; + firstDayOfWeek = state.firstDayOfWeek; + minDate = state.minDate; + maxDate = state.maxDate; + cacheCurrentPosition = state.cacheCurrentPosition; + showWeekDays = state.showWeekDays; + } + + /** + * Sets the first day of the week. + *

+ * Uses the {@link DayOfWeek} day constants. + * + * @param day The first day of the week as a {@link DayOfWeek} enum. + * @see java.util.Calendar + */ + public StateBuilder setFirstDayOfWeek(DayOfWeek day) { + this.firstDayOfWeek = day; + return this; + } + + /** + * Set calendar display mode. The default mode is Months. + * When switching between modes will select todays date, or the selected date, + * if selection mode is single. + * + * @param mode - calendar mode + */ + public StateBuilder setCalendarDisplayMode(CalendarMode mode) { + this.calendarMode = mode; + return this; + } + + /** + * @param date set the minimum selectable date, null for no minimum + */ + public StateBuilder setMinimumDate(@Nullable LocalDate date) { + setMinimumDate(CalendarDay.from(date)); + return this; + } + + /** + * @param calendar set the minimum selectable date, null for no minimum + */ + public StateBuilder setMinimumDate(@Nullable CalendarDay calendar) { + minDate = calendar; + return this; + } + + /** + * @param date set the maximum selectable date, null for no maximum + */ + public StateBuilder setMaximumDate(@Nullable LocalDate date) { + setMaximumDate(CalendarDay.from(date)); + return this; + } + + /** + * @param calendar set the maximum selectable date, null for no maximum + */ + public StateBuilder setMaximumDate(@Nullable CalendarDay calendar) { + maxDate = calendar; + return this; + } + + /** + * @param showWeekDays true to show week days names + */ + public StateBuilder setShowWeekDays(boolean showWeekDays) { + this.showWeekDays = showWeekDays; + return this; + } + + /** + * Use this method to enable saving the current position when switching + * between week and month mode. By default, the calendar update to the latest selected date + * or the current date. When set to true, the view will used the month that the calendar is + * currently on. + * + * @param cacheCurrentPosition Set to true to cache the current position, false otherwise. + */ + public StateBuilder isCacheCalendarPositionEnabled(final boolean cacheCurrentPosition) { + this.cacheCurrentPosition = cacheCurrentPosition; + return this; + } + + public void commit() { + MaterialCalendarView.this.commit(new State(this)); + } + } + + private void commit(State state) { + // Use the calendarDayToShow to determine which date to focus on for the case of switching between month and week views + CalendarDay calendarDayToShow = null; + if (adapter != null && state.cacheCurrentPosition) { + calendarDayToShow = adapter.getItem(pager.getCurrentItem()); + if (calendarMode != state.calendarMode) { + CalendarDay currentlySelectedDate = getSelectedDate(); + if (calendarMode == CalendarMode.MONTHS && currentlySelectedDate != null) { + // Going from months to weeks + LocalDate lastVisibleCalendar = calendarDayToShow.getDate(); + CalendarDay lastVisibleCalendarDay = CalendarDay.from(lastVisibleCalendar.plusDays(1)); + if (currentlySelectedDate.equals(calendarDayToShow) || + (currentlySelectedDate.isAfter(calendarDayToShow) && currentlySelectedDate.isBefore( + lastVisibleCalendarDay))) { + // Currently selected date is within view, so center on that + calendarDayToShow = currentlySelectedDate; + } + } else if (calendarMode == CalendarMode.WEEKS) { + // Going from weeks to months + LocalDate lastVisibleCalendar = calendarDayToShow.getDate(); + CalendarDay lastVisibleCalendarDay = CalendarDay.from(lastVisibleCalendar.plusDays(6)); + if (currentlySelectedDate != null && + (currentlySelectedDate.equals(calendarDayToShow) || currentlySelectedDate.equals( + lastVisibleCalendarDay) || + (currentlySelectedDate.isAfter(calendarDayToShow) + && currentlySelectedDate.isBefore(lastVisibleCalendarDay)))) { + // Currently selected date is within view, so center on that + calendarDayToShow = currentlySelectedDate; + } else { + calendarDayToShow = lastVisibleCalendarDay; + } + } + } + } + + this.state = state; + // Save states parameters + calendarMode = state.calendarMode; + firstDayOfWeek = state.firstDayOfWeek; + minDate = state.minDate; + maxDate = state.maxDate; + showWeekDays = state.showWeekDays; + + // Recreate adapter + final CalendarPagerAdapter newAdapter; + switch (calendarMode) { + case MONTHS: + newAdapter = new MonthPagerAdapter(this); + break; + case WEEKS: + newAdapter = new WeekPagerAdapter(this); + break; + default: + throw new IllegalArgumentException("Provided display mode which is not yet implemented"); + } + if (adapter == null) { + adapter = newAdapter; + } else { + adapter = adapter.migrateStateAndReturn(newAdapter); + } + adapter.setShowWeekDays(showWeekDays); + pager.setAdapter(adapter); + setRangeDates(minDate, maxDate); + + // Reset height params after mode change + int tileHeight = showWeekDays ? calendarMode.getVisibleWeeksCount() + DAY_NAMES_ROW + : calendarMode.getVisibleWeeksCount(); + pager.setLayoutParams(new LayoutParams(tileHeight)); + + setCurrentDate( + selectionMode == SELECTION_MODE_SINGLE && !adapter.getSelectedDates().isEmpty() + ? adapter.getSelectedDates().get(0) + : CalendarDay.today()); + + if (calendarDayToShow != null) { + pager.setCurrentItem(adapter.getIndexForDay(calendarDayToShow)); + } + + invalidateDecorators(); + updateUi(); + } + + /** + * Used for enabling or disabling views, while also changing the alpha. + * + * @param view The view to enable or disable. + * @param enable Whether to enable or disable the view. + */ + private static void enableView(final View view, final boolean enable) { + view.setEnabled(enable); + view.setAlpha(enable ? 1f : 0.1f); + } } diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/MonthPagerAdapter.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/MonthPagerAdapter.java index 1e205310..74d9d306 100644 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/MonthPagerAdapter.java +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/MonthPagerAdapter.java @@ -1,6 +1,9 @@ package com.prolificinteractive.materialcalendarview; import android.support.annotation.NonNull; + +import com.prolificinteractive.materialcalendarview.listeners.DateRangeIndex; + import org.threeten.bp.Period; /** diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/MonthView.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/MonthView.java index 1fae0818..65af3a86 100644 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/MonthView.java +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/MonthView.java @@ -2,7 +2,9 @@ import android.annotation.SuppressLint; import android.support.annotation.NonNull; + import java.util.Collection; + import org.threeten.bp.DayOfWeek; import org.threeten.bp.LocalDate; @@ -10,37 +12,40 @@ * Display a month of {@linkplain DayView}s and * seven {@linkplain WeekDayView}s. */ -@SuppressLint("ViewConstructor") class MonthView extends CalendarPagerView { - - public MonthView( - @NonNull final MaterialCalendarView view, - final CalendarDay month, - final DayOfWeek firstDayOfWeek, - final boolean showWeekDays) { - super(view, month, firstDayOfWeek, showWeekDays); - } - - @Override protected void buildDayViews( - final Collection dayViews, - final LocalDate calendar) { - LocalDate temp = calendar; - for (int r = 0; r < DEFAULT_MAX_WEEKS; r++) { - for (int i = 0; i < DEFAULT_DAYS_IN_WEEK; i++) { - addDayView(dayViews, temp); - temp = temp.plusDays(1); - } +@SuppressLint("ViewConstructor") +class MonthView extends CalendarPagerView { + + public MonthView( + @NonNull final MaterialCalendarView view, + final CalendarDay month, + final DayOfWeek firstDayOfWeek, + final boolean showWeekDays) { + super(view, month, firstDayOfWeek, showWeekDays); + } + + @Override + protected void buildDayViews(final Collection dayViews, final LocalDate calendar) { + LocalDate temp = calendar; + for (int r = 0; r < DEFAULT_MAX_WEEKS; r++) { + for (int i = 0; i < DEFAULT_DAYS_IN_WEEK; i++) { + addDayView(dayViews, temp); + if (temp != null) + temp = temp.plusDays(1); + } + } } - } - public CalendarDay getMonth() { - return getFirstViewDay(); - } + public CalendarDay getMonth() { + return getFirstViewDay(); + } - @Override protected boolean isDayEnabled(final CalendarDay day) { - return day.getMonth() == getFirstViewDay().getMonth(); - } + @Override + protected boolean isDayEnabled(final CalendarDay day) { + return day.getMonth() == getFirstViewDay().getMonth(); + } - @Override protected int getRows() { - return showWeekDays ? DEFAULT_MAX_WEEKS + DAY_NAMES_ROW : DEFAULT_MAX_WEEKS; - } + @Override + protected int getRows() { + return showWeekDays ? DEFAULT_MAX_WEEKS + DAY_NAMES_ROW : DEFAULT_MAX_WEEKS; + } } diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/OnDateLongClickListener.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/OnDateLongClickListener.java deleted file mode 100644 index e1fbc208..00000000 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/OnDateLongClickListener.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.prolificinteractive.materialcalendarview; - -import android.support.annotation.NonNull; - -/** - * The callback used to indicate a date has been long clicked. - */ -public interface OnDateLongClickListener { - - /** - * Called when a user long clicks on a day. - * There is no logic to prevent multiple calls for the same date and state. - * - * @param widget the view associated with this listener - * @param date the date that was long clicked. - */ - void onDateLongClick(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date); -} diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/OnDateSelectedListener.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/OnDateSelectedListener.java deleted file mode 100644 index e4ea640c..00000000 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/OnDateSelectedListener.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.prolificinteractive.materialcalendarview; - -import android.support.annotation.NonNull; - -/** - * The callback used to indicate a date has been selected or deselected - */ -public interface OnDateSelectedListener { - - /** - * Called when a user clicks on a day. - * There is no logic to prevent multiple calls for the same date and state. - * - * @param widget the view associated with this listener - * @param date the date that was selected or unselected - * @param selected true if the day is now selected, false otherwise - */ - void onDateSelected( - @NonNull MaterialCalendarView widget, - @NonNull CalendarDay date, - boolean selected); -} diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/OnMonthChangedListener.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/OnMonthChangedListener.java deleted file mode 100644 index 16f4b576..00000000 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/OnMonthChangedListener.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.prolificinteractive.materialcalendarview; - -/** - * The callback used to indicate the user changes the displayed month - */ -public interface OnMonthChangedListener { - - /** - * Called upon change of the selected day - * - * @param widget the view associated with this listener - * @param date the month picked, as the first day of the month - */ - void onMonthChanged(MaterialCalendarView widget, CalendarDay date); -} diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/OnRangeSelectedListener.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/OnRangeSelectedListener.java deleted file mode 100644 index 97c41715..00000000 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/OnRangeSelectedListener.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.prolificinteractive.materialcalendarview; - -import android.support.annotation.NonNull; -import java.util.List; - -/** - * The callback used to indicate a range has been selected - */ -public interface OnRangeSelectedListener { - - /** - * Called when a user selects a range of days. - * There is no logic to prevent multiple calls for the same date and state. - * - * @param widget the view associated with this listener - * @param dates the dates in the range, in ascending order - */ - void onRangeSelected(@NonNull MaterialCalendarView widget, @NonNull List dates); -} diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/TitleChanger.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/TitleChanger.java index 31cef265..69e3f4e2 100644 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/TitleChanger.java +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/TitleChanger.java @@ -10,140 +10,143 @@ import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.widget.TextView; + import com.prolificinteractive.materialcalendarview.format.TitleFormatter; +import com.prolificinteractive.materialcalendarview.listeners.AnimatorListener; class TitleChanger { - public static final int DEFAULT_ANIMATION_DELAY = 400; - public static final int DEFAULT_Y_TRANSLATION_DP = 20; - - private final TextView title; - @NonNull private TitleFormatter titleFormatter = TitleFormatter.DEFAULT; - - private final int animDelay; - private final int animDuration; - private final int translate; - private final Interpolator interpolator = new DecelerateInterpolator(2f); + public static final int DEFAULT_ANIMATION_DELAY = 400; + public static final int DEFAULT_Y_TRANSLATION_DP = 20; - private int orientation = MaterialCalendarView.VERTICAL; + private final TextView title; + @NonNull + private TitleFormatter titleFormatter = TitleFormatter.DEFAULT; - private long lastAnimTime = 0; - private CalendarDay previousMonth = null; + private final int animDelay; + private final int animDuration; + private final int translate; + private final Interpolator interpolator = new DecelerateInterpolator(2f); - public TitleChanger(TextView title) { - this.title = title; + private int orientation = MaterialCalendarView.VERTICAL; - Resources res = title.getResources(); + private long lastAnimTime = 0; + private CalendarDay previousMonth = null; - animDelay = DEFAULT_ANIMATION_DELAY; + public TitleChanger(TextView title) { + this.title = title; - animDuration = res.getInteger(android.R.integer.config_shortAnimTime) / 2; + Resources res = title.getResources(); - translate = (int) TypedValue.applyDimension( - TypedValue.COMPLEX_UNIT_DIP, DEFAULT_Y_TRANSLATION_DP, res.getDisplayMetrics() - ); - } + animDelay = DEFAULT_ANIMATION_DELAY; - public void change(final CalendarDay currentMonth) { - long currentTime = System.currentTimeMillis(); + animDuration = res.getInteger(android.R.integer.config_shortAnimTime) / 2; - if (currentMonth == null) { - return; + translate = (int) TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_DIP, DEFAULT_Y_TRANSLATION_DP, res.getDisplayMetrics() + ); } - if (TextUtils.isEmpty(title.getText()) || (currentTime - lastAnimTime) < animDelay) { - doChange(currentTime, currentMonth, false); - } + public void change(final CalendarDay currentMonth) { + long currentTime = System.currentTimeMillis(); - if (currentMonth.equals(previousMonth) || - (currentMonth.getMonth() == previousMonth.getMonth() - && currentMonth.getYear() == previousMonth.getYear())) { - return; - } + if (currentMonth == null) { + return; + } - doChange(currentTime, currentMonth, true); - } + if (TextUtils.isEmpty(title.getText()) || (currentTime - lastAnimTime) < animDelay) { + doChange(currentTime, currentMonth, false); + } - private void doChange(final long now, final CalendarDay currentMonth, boolean animate) { + if (previousMonth == null || currentMonth.equals(previousMonth) || + (currentMonth.getMonth() == previousMonth.getMonth() + && currentMonth.getYear() == previousMonth.getYear())) { + return; + } - title.animate().cancel(); - doTranslation(title, 0); + doChange(currentTime, currentMonth, true); + } - title.setAlpha(1); - lastAnimTime = now; + private void doChange(final long now, final CalendarDay currentMonth, boolean animate) { - final CharSequence newTitle = titleFormatter.format(currentMonth); + title.animate().cancel(); + doTranslation(title, 0); - if (!animate) { - title.setText(newTitle); - } else { - final int translation = translate * (previousMonth.isBefore(currentMonth) ? 1 : -1); - final ViewPropertyAnimator viewPropertyAnimator = title.animate(); + title.setAlpha(1); + lastAnimTime = now; - if (orientation == MaterialCalendarView.HORIZONTAL) { - viewPropertyAnimator.translationX(translation * -1); - } else { - viewPropertyAnimator.translationY(translation * -1); - } + final CharSequence newTitle = titleFormatter.format(currentMonth); - viewPropertyAnimator - .alpha(0) - .setDuration(animDuration) - .setInterpolator(interpolator) - .setListener(new AnimatorListener() { + if (!animate) { + title.setText(newTitle); + } else { + final int translation = translate * (previousMonth.isBefore(currentMonth) ? 1 : -1); + final ViewPropertyAnimator viewPropertyAnimator = title.animate(); - @Override - public void onAnimationCancel(Animator animator) { - doTranslation(title, 0); - title.setAlpha(1); + if (orientation == MaterialCalendarView.HORIZONTAL) { + viewPropertyAnimator.translationX(translation * -1); + } else { + viewPropertyAnimator.translationY(translation * -1); } - @Override - public void onAnimationEnd(Animator animator) { - title.setText(newTitle); - doTranslation(title, translation); - - final ViewPropertyAnimator viewPropertyAnimator = title.animate(); - if (orientation == MaterialCalendarView.HORIZONTAL) { - viewPropertyAnimator.translationX(0); - } else { - viewPropertyAnimator.translationY(0); - } - - viewPropertyAnimator - .alpha(1) - .setDuration(animDuration) - .setInterpolator(interpolator) - .setListener(new AnimatorListener()) - .start(); - } - }).start(); + viewPropertyAnimator + .alpha(0) + .setDuration(animDuration) + .setInterpolator(interpolator) + .setListener(new AnimatorListener() { + + @Override + public void onAnimationCancel(Animator animator) { + doTranslation(title, 0); + title.setAlpha(1); + } + + @Override + public void onAnimationEnd(Animator animator) { + title.setText(newTitle); + doTranslation(title, translation); + + final ViewPropertyAnimator viewPropertyAnimator = title.animate(); + if (orientation == MaterialCalendarView.HORIZONTAL) { + viewPropertyAnimator.translationX(0); + } else { + viewPropertyAnimator.translationY(0); + } + + viewPropertyAnimator + .alpha(1) + .setDuration(animDuration) + .setInterpolator(interpolator) + .setListener(new AnimatorListener()) + .start(); + } + }).start(); + } + + previousMonth = currentMonth; } - previousMonth = currentMonth; - } - - private void doTranslation(final TextView title, final int translate) { - if (orientation == MaterialCalendarView.HORIZONTAL) { - title.setTranslationX(translate); - } else { - title.setTranslationY(translate); + private void doTranslation(final TextView title, final int translate) { + if (orientation == MaterialCalendarView.HORIZONTAL) { + title.setTranslationX(translate); + } else { + title.setTranslationY(translate); + } } - } - public void setTitleFormatter(@Nullable final TitleFormatter titleFormatter) { - this.titleFormatter = titleFormatter == null ? TitleFormatter.DEFAULT : titleFormatter; - } + public void setTitleFormatter(@Nullable final TitleFormatter titleFormatter) { + this.titleFormatter = titleFormatter == null ? TitleFormatter.DEFAULT : titleFormatter; + } - public void setOrientation(int orientation) { - this.orientation = orientation; - } + public void setOrientation(int orientation) { + this.orientation = orientation; + } - public int getOrientation() { - return orientation; - } + public int getOrientation() { + return orientation; + } - public void setPreviousMonth(CalendarDay previousMonth) { - this.previousMonth = previousMonth; - } + public void setPreviousMonth(CalendarDay previousMonth) { + this.previousMonth = previousMonth; + } } diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/WeekPagerAdapter.java b/library/src/main/java/com/prolificinteractive/materialcalendarview/WeekPagerAdapter.java index 413038da..c455f17a 100644 --- a/library/src/main/java/com/prolificinteractive/materialcalendarview/WeekPagerAdapter.java +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/WeekPagerAdapter.java @@ -1,6 +1,9 @@ package com.prolificinteractive.materialcalendarview; import android.support.annotation.NonNull; + +import com.prolificinteractive.materialcalendarview.listeners.DateRangeIndex; + import org.threeten.bp.DayOfWeek; import org.threeten.bp.LocalDate; import org.threeten.bp.temporal.ChronoUnit; diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/AnimatorListener.kt b/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/AnimatorListener.kt new file mode 100644 index 00000000..7b5dd31a --- /dev/null +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/AnimatorListener.kt @@ -0,0 +1,22 @@ +package com.prolificinteractive.materialcalendarview.listeners; + +import android.animation.Animator; + +open class AnimatorListener : Animator.AnimatorListener { + override fun onAnimationStart(animation: Animator) { + + } + + override fun onAnimationEnd(animation: Animator) { + + } + + override fun onAnimationCancel(animation: Animator) { + + } + + override fun onAnimationRepeat(animation: Animator) { + + } + +} diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/DateRangeIndex.kt b/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/DateRangeIndex.kt new file mode 100644 index 00000000..069b55d5 --- /dev/null +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/DateRangeIndex.kt @@ -0,0 +1,25 @@ +package com.prolificinteractive.materialcalendarview.listeners; + +import com.prolificinteractive.materialcalendarview.CalendarDay; + +/** + * Use math to calculate first days of months or weeks by position from a minimum date (and first + * day of week in case of weekly range). + */ +public interface DateRangeIndex { + + /** + * Count of pages displayed between 2 dates. + */ + fun getCount(): Int; + + /** + * Index of the page where the date is displayed. + */ + fun indexOf(day: CalendarDay): Int; + + /** + * Get the first date at the position within the index. + */ + fun getItem(position: Int): CalendarDay; +} diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/DayViewDecorator.kt b/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/DayViewDecorator.kt new file mode 100644 index 00000000..763895f1 --- /dev/null +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/DayViewDecorator.kt @@ -0,0 +1,25 @@ +package com.prolificinteractive.materialcalendarview.listeners; + +import com.prolificinteractive.materialcalendarview.CalendarDay; +import com.prolificinteractive.materialcalendarview.DayViewFacade; + +/** + * Decorate Day views with drawables and text manipulation + */ +public interface DayViewDecorator { + + /** + * Determine if a specific day should be decorated + * + * @param day {@linkplain CalendarDay} to possibly decorate + * @return true if this decorator should be applied to the provided day + */ + fun shouldDecorate(day: CalendarDay): Boolean; + + /** + * Set decoration options onto a facade to be applied to all relevant days + * + * @param view View to decorate + */ + fun decorate(view: DayViewFacade); +} diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/OnDateLongClickListener.kt b/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/OnDateLongClickListener.kt new file mode 100644 index 00000000..e78297d9 --- /dev/null +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/OnDateLongClickListener.kt @@ -0,0 +1,21 @@ +package com.prolificinteractive.materialcalendarview.listeners; + +import android.support.annotation.NonNull; + +import com.prolificinteractive.materialcalendarview.CalendarDay; +import com.prolificinteractive.materialcalendarview.MaterialCalendarView; + +/** + * The callback used to indicate a date has been long clicked. + */ +public interface OnDateLongClickListener { + + /** + * Called when a user long clicks on a day. + * There is no logic to prevent multiple calls for the same date and state. + * + * @param widget the view associated with this listener + * @param date the date that was long clicked. + */ + fun onDateLongClick(widget: MaterialCalendarView, date: CalendarDay); +} diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/OnDateSelectedListener.kt b/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/OnDateSelectedListener.kt new file mode 100644 index 00000000..b8753303 --- /dev/null +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/OnDateSelectedListener.kt @@ -0,0 +1,22 @@ +package com.prolificinteractive.materialcalendarview.listeners; + +import android.support.annotation.NonNull; + +import com.prolificinteractive.materialcalendarview.CalendarDay; +import com.prolificinteractive.materialcalendarview.MaterialCalendarView; + +/** + * The callback used to indicate a date has been selected or deselected + */ +public interface OnDateSelectedListener { + + /** + * Called when a user clicks on a day. + * There is no logic to prevent multiple calls for the same date and state. + * + * @param widget the view associated with this listener + * @param date the date that was selected or unselected + * @param selected true if the day is now selected, false otherwise + */ + fun onDateSelected(widget: MaterialCalendarView, date: CalendarDay, selected: Boolean); +} diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/OnMonthChangedListener.kt b/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/OnMonthChangedListener.kt new file mode 100644 index 00000000..1de0340e --- /dev/null +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/OnMonthChangedListener.kt @@ -0,0 +1,18 @@ +package com.prolificinteractive.materialcalendarview.listeners; + +import com.prolificinteractive.materialcalendarview.CalendarDay; +import com.prolificinteractive.materialcalendarview.MaterialCalendarView; + +/** + * The callback used to indicate the user changes the displayed month + */ +public interface OnMonthChangedListener { + + /** + * Called upon change of the selected day + * + * @param widget the view associated with this listener + * @param date the month picked, as the first day of the month + */ + fun onMonthChanged(widget: MaterialCalendarView, date: CalendarDay); +} diff --git a/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/OnRangeSelectedListener.kt b/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/OnRangeSelectedListener.kt new file mode 100644 index 00000000..93e55de8 --- /dev/null +++ b/library/src/main/java/com/prolificinteractive/materialcalendarview/listeners/OnRangeSelectedListener.kt @@ -0,0 +1,23 @@ +package com.prolificinteractive.materialcalendarview.listeners; + +import android.support.annotation.NonNull; + +import com.prolificinteractive.materialcalendarview.CalendarDay; +import com.prolificinteractive.materialcalendarview.MaterialCalendarView; + +import java.util.List; + +/** + * The callback used to indicate a range has been selected + */ +public interface OnRangeSelectedListener { + + /** + * Called when a user selects a range of days. + * There is no logic to prevent multiple calls for the same date and state. + * + * @param widget the view associated with this listener + * @param dates the dates in the range, in ascending order + */ + fun onRangeSelected(widget: MaterialCalendarView, dates: MutableList); +} diff --git a/library/src/test/java/com/prolificinteractive/materialcalendarview/WeeklyRangeIndexTest.java b/library/src/test/java/com/prolificinteractive/materialcalendarview/WeeklyRangeIndexTest.java index 2afdc5fd..92f4edd8 100644 --- a/library/src/test/java/com/prolificinteractive/materialcalendarview/WeeklyRangeIndexTest.java +++ b/library/src/test/java/com/prolificinteractive/materialcalendarview/WeeklyRangeIndexTest.java @@ -1,5 +1,7 @@ package com.prolificinteractive.materialcalendarview; +import com.prolificinteractive.materialcalendarview.listeners.DateRangeIndex; + import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/sample/build.gradle b/sample/build.gradle index 01c0408f..ca652710 100644 --- a/sample/build.gradle +++ b/sample/build.gradle @@ -1,4 +1,5 @@ apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' android { compileSdkVersion rootProject.ext.compileSdkVersion @@ -34,4 +35,8 @@ dependencies { implementation rootProject.ext.recyclerviewV7 implementation rootProject.ext.butterknife annotationProcessor rootProject.ext.butterknifeCompiler + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" +} +repositories { + mavenCentral() } diff --git a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/BasicActivity.java b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/BasicActivity.java index e3168c13..ce997672 100644 --- a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/BasicActivity.java +++ b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/BasicActivity.java @@ -9,9 +9,9 @@ import butterknife.ButterKnife; import com.prolificinteractive.materialcalendarview.CalendarDay; import com.prolificinteractive.materialcalendarview.MaterialCalendarView; -import com.prolificinteractive.materialcalendarview.OnDateLongClickListener; -import com.prolificinteractive.materialcalendarview.OnDateSelectedListener; -import com.prolificinteractive.materialcalendarview.OnMonthChangedListener; +import com.prolificinteractive.materialcalendarview.listeners.OnDateLongClickListener; +import com.prolificinteractive.materialcalendarview.listeners.OnDateSelectedListener; +import com.prolificinteractive.materialcalendarview.listeners.OnMonthChangedListener; import org.threeten.bp.format.DateTimeFormatter; /** diff --git a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/BasicActivityDecorated.java b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/BasicActivityDecorated.java index d67a5b8b..6250149d 100644 --- a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/BasicActivityDecorated.java +++ b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/BasicActivityDecorated.java @@ -9,7 +9,7 @@ import butterknife.ButterKnife; import com.prolificinteractive.materialcalendarview.CalendarDay; import com.prolificinteractive.materialcalendarview.MaterialCalendarView; -import com.prolificinteractive.materialcalendarview.OnDateSelectedListener; +import com.prolificinteractive.materialcalendarview.listeners.OnDateSelectedListener; import com.prolificinteractive.materialcalendarview.sample.decorators.EventDecorator; import com.prolificinteractive.materialcalendarview.sample.decorators.HighlightWeekendsDecorator; import com.prolificinteractive.materialcalendarview.sample.decorators.MySelectorDecorator; diff --git a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/CustomTileDimensions.java b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/CustomTileDimensions.java index 8d60de5e..ea9c369b 100644 --- a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/CustomTileDimensions.java +++ b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/CustomTileDimensions.java @@ -12,7 +12,7 @@ import butterknife.ButterKnife; import butterknife.OnClick; import com.prolificinteractive.materialcalendarview.CalendarDay; -import com.prolificinteractive.materialcalendarview.DayViewDecorator; +import com.prolificinteractive.materialcalendarview.listeners.DayViewDecorator; import com.prolificinteractive.materialcalendarview.DayViewFacade; import com.prolificinteractive.materialcalendarview.MaterialCalendarView; diff --git a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/DialogsActivity.java b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/DialogsActivity.java index befb6ef9..51d8c577 100644 --- a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/DialogsActivity.java +++ b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/DialogsActivity.java @@ -13,7 +13,7 @@ import butterknife.OnClick; import com.prolificinteractive.materialcalendarview.CalendarDay; import com.prolificinteractive.materialcalendarview.MaterialCalendarView; -import com.prolificinteractive.materialcalendarview.OnDateSelectedListener; +import com.prolificinteractive.materialcalendarview.listeners.OnDateSelectedListener; import org.threeten.bp.format.DateTimeFormatter; /** diff --git a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/DisableDaysActivity.java b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/DisableDaysActivity.java index d164553b..5e39dcec 100644 --- a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/DisableDaysActivity.java +++ b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/DisableDaysActivity.java @@ -5,7 +5,7 @@ import butterknife.BindView; import butterknife.ButterKnife; import com.prolificinteractive.materialcalendarview.CalendarDay; -import com.prolificinteractive.materialcalendarview.DayViewDecorator; +import com.prolificinteractive.materialcalendarview.listeners.DayViewDecorator; import com.prolificinteractive.materialcalendarview.DayViewFacade; import com.prolificinteractive.materialcalendarview.MaterialCalendarView; import org.threeten.bp.LocalDate; diff --git a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/DynamicSettersActivity.java b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/DynamicSettersActivity.java index 516cdd37..5b2bd3f9 100644 --- a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/DynamicSettersActivity.java +++ b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/DynamicSettersActivity.java @@ -23,7 +23,7 @@ import com.prolificinteractive.materialcalendarview.CalendarDay; import com.prolificinteractive.materialcalendarview.CalendarMode; import com.prolificinteractive.materialcalendarview.MaterialCalendarView; -import com.prolificinteractive.materialcalendarview.OnDateLongClickListener; +import com.prolificinteractive.materialcalendarview.listeners.OnDateLongClickListener; import java.util.Random; import org.threeten.bp.DayOfWeek; import org.threeten.bp.format.DateTimeFormatter; diff --git a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/RotationActivity.java b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/RotationActivity.java index 1db75395..3314ea09 100644 --- a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/RotationActivity.java +++ b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/RotationActivity.java @@ -8,8 +8,8 @@ import butterknife.ButterKnife; import com.prolificinteractive.materialcalendarview.CalendarDay; import com.prolificinteractive.materialcalendarview.MaterialCalendarView; -import com.prolificinteractive.materialcalendarview.OnDateLongClickListener; -import com.prolificinteractive.materialcalendarview.OnMonthChangedListener; +import com.prolificinteractive.materialcalendarview.listeners.OnDateLongClickListener; +import com.prolificinteractive.materialcalendarview.listeners.OnMonthChangedListener; import org.threeten.bp.format.DateTimeFormatter; /** diff --git a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/SelectionModesActivity.java b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/SelectionModesActivity.java index 45135558..7bc59f50 100644 --- a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/SelectionModesActivity.java +++ b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/SelectionModesActivity.java @@ -13,8 +13,8 @@ import com.prolificinteractive.materialcalendarview.CalendarDay; import com.prolificinteractive.materialcalendarview.CalendarMode; import com.prolificinteractive.materialcalendarview.MaterialCalendarView; -import com.prolificinteractive.materialcalendarview.OnDateSelectedListener; -import com.prolificinteractive.materialcalendarview.OnRangeSelectedListener; +import com.prolificinteractive.materialcalendarview.listeners.OnDateSelectedListener; +import com.prolificinteractive.materialcalendarview.listeners.OnRangeSelectedListener; import com.prolificinteractive.materialcalendarview.sample.decorators.RangeDayDecorator; import java.util.List; import org.threeten.bp.format.DateTimeFormatter; diff --git a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/SwappableBasicActivityDecorated.java b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/SwappableBasicActivityDecorated.java index aaa5ba6f..ec072b5d 100644 --- a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/SwappableBasicActivityDecorated.java +++ b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/SwappableBasicActivityDecorated.java @@ -9,7 +9,7 @@ import com.prolificinteractive.materialcalendarview.CalendarDay; import com.prolificinteractive.materialcalendarview.CalendarMode; import com.prolificinteractive.materialcalendarview.MaterialCalendarView; -import com.prolificinteractive.materialcalendarview.OnDateSelectedListener; +import com.prolificinteractive.materialcalendarview.listeners.OnDateSelectedListener; import com.prolificinteractive.materialcalendarview.sample.decorators.HighlightWeekendsDecorator; import com.prolificinteractive.materialcalendarview.sample.decorators.MySelectorDecorator; import com.prolificinteractive.materialcalendarview.sample.decorators.OneDayDecorator; diff --git a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/EventDecorator.java b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/EventDecorator.java index 95079557..e0cda6c6 100644 --- a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/EventDecorator.java +++ b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/EventDecorator.java @@ -1,7 +1,7 @@ package com.prolificinteractive.materialcalendarview.sample.decorators; import com.prolificinteractive.materialcalendarview.CalendarDay; -import com.prolificinteractive.materialcalendarview.DayViewDecorator; +import com.prolificinteractive.materialcalendarview.listeners.DayViewDecorator; import com.prolificinteractive.materialcalendarview.DayViewFacade; import com.prolificinteractive.materialcalendarview.spans.DotSpan; import java.util.Collection; diff --git a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/HighlightWeekendsDecorator.java b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/HighlightWeekendsDecorator.java index 22e5b500..8777efce 100644 --- a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/HighlightWeekendsDecorator.java +++ b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/HighlightWeekendsDecorator.java @@ -4,7 +4,7 @@ import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import com.prolificinteractive.materialcalendarview.CalendarDay; -import com.prolificinteractive.materialcalendarview.DayViewDecorator; +import com.prolificinteractive.materialcalendarview.listeners.DayViewDecorator; import com.prolificinteractive.materialcalendarview.DayViewFacade; import org.threeten.bp.DayOfWeek; diff --git a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/MySelectorDecorator.java b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/MySelectorDecorator.java index f35b3bcc..3e8ad79f 100644 --- a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/MySelectorDecorator.java +++ b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/MySelectorDecorator.java @@ -3,7 +3,7 @@ import android.app.Activity; import android.graphics.drawable.Drawable; import com.prolificinteractive.materialcalendarview.CalendarDay; -import com.prolificinteractive.materialcalendarview.DayViewDecorator; +import com.prolificinteractive.materialcalendarview.listeners.DayViewDecorator; import com.prolificinteractive.materialcalendarview.DayViewFacade; import com.prolificinteractive.materialcalendarview.sample.R; diff --git a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/OneDayDecorator.java b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/OneDayDecorator.java index e6735f4b..c654bdd0 100644 --- a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/OneDayDecorator.java +++ b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/OneDayDecorator.java @@ -4,7 +4,7 @@ import android.text.style.RelativeSizeSpan; import android.text.style.StyleSpan; import com.prolificinteractive.materialcalendarview.CalendarDay; -import com.prolificinteractive.materialcalendarview.DayViewDecorator; +import com.prolificinteractive.materialcalendarview.listeners.DayViewDecorator; import com.prolificinteractive.materialcalendarview.DayViewFacade; import com.prolificinteractive.materialcalendarview.MaterialCalendarView; import org.threeten.bp.LocalDate; diff --git a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/RangeDayDecorator.java b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/RangeDayDecorator.java index dfe3dd7f..ef4add92 100644 --- a/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/RangeDayDecorator.java +++ b/sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/decorators/RangeDayDecorator.java @@ -3,7 +3,7 @@ import android.content.Context; import android.graphics.drawable.Drawable; import com.prolificinteractive.materialcalendarview.CalendarDay; -import com.prolificinteractive.materialcalendarview.DayViewDecorator; +import com.prolificinteractive.materialcalendarview.listeners.DayViewDecorator; import com.prolificinteractive.materialcalendarview.DayViewFacade; import com.prolificinteractive.materialcalendarview.MaterialCalendarView; import com.prolificinteractive.materialcalendarview.sample.R;