Repository: premkumarroyal/MonthAndYearPicker Branch: master Commit: 8f8f5e710351 Files: 50 Total size: 111.2 KB Directory structure: gitextract_z2b1z__v/ ├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── monthandyearpicker/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── com/ │ │ └── whiteelephant/ │ │ └── monthpicker/ │ │ ├── MonthPickerDialog.java │ │ ├── MonthPickerView.java │ │ ├── MonthView.java │ │ ├── MonthViewAdapter.java │ │ └── YearPickerView.java │ └── res/ │ ├── drawable-v21/ │ │ └── month_ripplr.xml │ ├── layout/ │ │ ├── month_picker_dialog.xml │ │ ├── month_picker_view.xml │ │ ├── month_view_header.xml │ │ └── year_label_text_view.xml │ ├── layout-land/ │ │ ├── month_picker_view.xml │ │ └── month_view_header.xml │ ├── layout-v11/ │ │ ├── month_picker_view.xml │ │ └── year_label_text_view.xml │ ├── values/ │ │ ├── attrs.xml │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── values-w820dp/ │ └── dimens.xml ├── sample/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ ├── androidTest/ │ │ └── java/ │ │ └── com/ │ │ └── whitelephant/ │ │ └── monthpickersample/ │ │ └── ExampleInstrumentedTest.java │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── com/ │ │ │ └── whiteelephant/ │ │ │ └── monthpickersample/ │ │ │ └── MainActivity.java │ │ └── res/ │ │ ├── layout/ │ │ │ ├── activity_bottle.xml │ │ │ ├── activity_choose_month.xml │ │ │ ├── activity_choose_year.xml │ │ │ └── activity_main.xml │ │ ├── values/ │ │ │ ├── colors.xml │ │ │ ├── dimens.xml │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ └── values-w820dp/ │ │ └── dimens.xml │ └── test/ │ └── java/ │ └── com/ │ └── whiteelphant/ │ └── monthpickersample/ │ └── ExampleUnitTest.java └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.iml .gradle /local.properties /bintray.properties /.idea/workspace.xml /.idea/libraries .DS_Store /build /captures .externalNativeBuild .classpath .project .settings eclipsebin /A_Improvments.txt bin gen build out lib .idea *.iml classes obj .DS_Store # Gradle .gradle jniLibs build reports # Built application files *.apk *.ap_ # Files for the ART/Dalvik VM *.dex # Java class files *.class # Generated files bin/ gen/ out/ # Gradle files .gradle/ build/ # Local configuration file (sdk path, etc) local.properties bintray.properties # Proguard folder generated by Eclipse proguard/ # Log Files *.log # Android Studio Navigation editor temp files .navigation/ # Android Studio captures folder captures/ # Intellij *.iml .idea/workspace.xml # Keystore files *.jks improvments A_Improvments.java ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2018 Prem Kumar Koti Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # MonthAndYearPicker Month and Year Picker allow user to pick only month and year or only month or only year as required. You will get notified for all action's such as on selection of date, on selection of month and on section of year. ## Sample Project output: ![MonthAndYearPicker](https://github.com/premkumarroyal/MonthAndYearPicker/blob/master/sample/src/main/res/raw/datepicker.gif?raw=true "Month and Year Picker") ![MonthAndYearPicker](https://j.gifs.com/nZpE4P.gif?raw=true "Choose Month") ![MonthAndYearPicker](https://github.com/premkumarroyal/MonthAndYearPicker/blob/master/sample/src/main/res/raw/choose_year.gif?raw=true "Choose Year") ![MonthAndYearPicker](https://j.gifs.com/LgoKEv.gif?raw=true "Choose Quantity") # Code MonthPickerDialog.Builder builder = new MonthPickerDialog.Builder(MainActivity.this, new MonthPickerDialog.OnDateSetListener() { @Override public void onDateSet(int selectedMonth, int selectedYear) { // on date set } }, today.get(Calendar.YEAR), today.get(Calendar.MONTH)); builder.setActivatedMonth(Calendar.JULY) .setMinYear(1990) .setActivatedYear(2017) .setMaxYear(2030) .setMinMonth(Calendar.FEBRUARY) .setTitle("Select trading month") .setMonthRange(Calendar.FEBRUARY, Calendar.NOVEMBER) // .setMaxMonth(Calendar.OCTOBER) // .setYearRange(1890, 1890) // .setMonthAndYearRange(Calendar.FEBRUARY, Calendar.OCTOBER, 1890, 1890) //.showMonthOnly() // .showYearOnly() .setOnMonthChangedListener(new MonthPickerDialog.OnMonthChangedListener() { @Override public void onMonthChanged(int selectedMonth) { // on month selected } }) .setOnYearChangedListener(new MonthPickerDialog.OnYearChangedListener() { @Override public void onYearChanged(int selectedYear) { // on year selected } }) .build() .show(); ## Listeners setOnMonthChangedListener(OnMonthChangedListener()); setOnYearChangedListener(OnYearChangedListener()); ## Methods Methods | Docs ------------ | ------------- setMaxMonth(int maxMonth) | Maximum month that user can select. setMinMonth(int minMonth) | Minimum month that user can select. setMonthRange(int minMonth, int maxMonth) | set both max and min sections. setActivatedMonth(activatedMonth) | selected the month when picker opens. setMaxYear(int maxYear) | Maximum year that will be shown in picker. setMinYear(int minYear) | Minimum year that will be shown in picker. setYearRange(int minYear, int maxYear) | set both max and min selections. setActivatedYear(activatedYear) | selected the year when picker opens. setMonthAndYearRange(int minMonth, int maxMonth, int minYear, int maxYear) | set month and year min and max values at once. showMonthOnly() | Only month selection will be shown. showYearOnly() | Only year selection will be shown. setTitle(String title) | set the title for Month Picker Dialog. By default title will be hidden, it will be visible if value set. setOnMonthChangedListener(MonthPickerDialog.OnMonthChangedListener onMonthChange); | Listener for select month setOnYearChangedListener(MonthPickerDialog.OnYearChangedListener onYearChange); | Listener for year select year ## Styling Month and Year picker by default pick the color from theme if you declared colorAccent. If you want to change color's you can override the theme as below. ## Usage Add Gradle Dependency in your build.gradle file compile 'com.whiteelephant:monthandyearpicker:1.3.0' or Maven com.whiteelephant monthandyearpicker 1.3.0 pom ================================================ FILE: build.gradle ================================================ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() google() } dependencies { classpath 'com.android.tools.build:gradle:3.1.3' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.2' classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1' } } allprojects { repositories { jcenter() google() } } task clean(type: Delete) { delete rootProject.buildDir } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Wed May 30 19:50:57 IST 2018 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip ================================================ FILE: gradle.properties ================================================ # Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. # Default value: -Xmx10248m -XX:MaxPermSize=256m # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true ================================================ FILE: gradlew ================================================ #!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null 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 # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock 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 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 ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((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" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" ================================================ FILE: gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @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 DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line 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% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: monthandyearpicker/.gitignore ================================================ /build ================================================ FILE: monthandyearpicker/build.gradle ================================================ apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' apply plugin: 'com.jfrog.bintray' version = "1.3.0" android { compileSdkVersion 27 buildToolsVersion '27.0.3' defaultConfig { minSdkVersion 14 targetSdkVersion 27 versionCode 1 versionName "1.3.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } ext { def v_bintrayRepo = '' def v_bintrayName = '' def v_publishedGroupId = '' def v_libraryName = '' def v_artifact = '' def v_libraryDescription = '' def v_gitUrl = '' def v_libraryVersion = '' def v_developerId = '' def v_developerName = '' def v_developerEmail = '' def versionPropsFile = file('bintray.properties') def Properties versionProps = new Properties() if (versionPropsFile.canRead()) { versionProps.load(new FileInputStream(versionPropsFile)) v_bintrayRepo = versionProps['bintrayRepo'].toString() v_bintrayName = versionProps['bintrayName'].toString() v_publishedGroupId = versionProps['publishedGroupId'].toString() v_libraryName = versionProps['libraryName'].toString() v_artifact = versionProps['artifact'].toString() v_libraryDescription = versionProps['libraryDescription'].toString() v_gitUrl = versionProps['gitUrl'].toString() v_libraryVersion = versionProps['libraryVersion'].toString() v_developerId = versionProps['developerId'].toString() v_developerName = versionProps['developerName'].toString() v_developerEmail = versionProps['developerEmail'].toString() } else { throw new FileNotFoundException("Could not read bintray.properties!") } bintrayRepo = "${v_bintrayRepo}" bintrayName = "${v_bintrayName}" publishedGroupId = "${v_publishedGroupId}" libraryName = "${v_libraryName}" artifact = "${v_artifact}" libraryDescription = "${v_libraryDescription}" siteUrl = '' gitUrl = "${v_gitUrl}" libraryVersion = "${v_libraryVersion}" developerId = "${v_developerId}" developerName = "${v_developerName}" developerEmail = "${v_developerEmail}" licenseName = 'The Apache Software License, Version 2.0' licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt' allLicenses = ["Apache-2.0"] } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) testImplementation 'junit:junit:4.12' implementation 'com.android.support:appcompat-v7:27.0.1' implementation 'com.android.support:design:27.0.1' } apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/installv1.gradle' apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/bintrayv1.gradle' ================================================ FILE: monthandyearpicker/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in C:\Users\Prem\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ================================================ FILE: monthandyearpicker/src/main/AndroidManifest.xml ================================================ ================================================ FILE: monthandyearpicker/src/main/java/com/whiteelephant/monthpicker/MonthPickerDialog.java ================================================ package com.whiteelephant.monthpicker; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.res.Configuration; import android.support.annotation.IntRange; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.DatePicker; import android.widget.DatePicker.OnDateChangedListener; import com.example.prem.firstpitch.R; import java.util.Calendar; public class MonthPickerDialog extends AlertDialog implements OnClickListener, OnDateChangedListener { private final MonthPickerView _monthPicker; private final OnDateSetListener _callBack; private View view; /** * @param context The context the dialog is to run in. * @param callBack How the parent is notified that the date is set. * @param year The initial year of the dialog. * @param monthOfYear The initial month of the dialog. */ private MonthPickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear) { this(context, 0, callBack, year, monthOfYear); } @Override public void show() { if (view != null) { if (this.getContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); if (getWindow() != null) { lp.copyFrom(getWindow().getAttributes()); lp.width = (int) (this.getContext().getResources().getDisplayMetrics().widthPixels * 0.94); lp.height = (int) (this.getContext().getResources().getDisplayMetrics().heightPixels * 0.94); // show the dialog as per super implementation super.show(); // now dialog attached to window so apply the size getWindow().setLayout(lp.width, lp.height); } return; }else { dismiss(); } } super.show(); } /** * @param context The context the dialog is to run in. * @param theme the theme to apply to this dialog * @param callBack How the parent is notified that the date is set. * @param year The initial year of the dialog. * @param monthOfYear The initial month of the dialog. */ private MonthPickerDialog(Context context, int theme, OnDateSetListener callBack, int year, int monthOfYear) { super(context, theme); _callBack = callBack; LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.month_picker_dialog, null); setView(view); _monthPicker = (MonthPickerView) view.findViewById(R.id.monthPicker); _monthPicker.setOnDateListener(new MonthPickerView.OnDateSet() { @Override public void onDateSet() { tryNotifyDateSet(); MonthPickerDialog.this.dismiss(); } }); _monthPicker.setOnCancelListener(new MonthPickerView.OnCancel() { @Override public void onCancel() { MonthPickerDialog.this.dismiss(); } }); // to show dialog bigger view in landscape mode we are increasing the // height and width of the dialog. If we do that android don't dismiss the dialog after // rotation and try to render landscape UI in portrait mode which is not correct. // so dismissing the dialog on each time when orientation changes. _monthPicker.setOnConfigurationChanged(new OnConfigChangeListener() { @Override public void onConfigChange() { dismiss(); } }); _monthPicker.init(year, monthOfYear); } @Override public void onClick(DialogInterface dialog, int which) { tryNotifyDateSet(); } @Override public void onDateChanged(DatePicker view, int year, int month, int day) { _monthPicker.init(year, month); } /** * Gets the {@link DatePicker} contained in this dialog. * * @return The calendar view. */ public MonthPickerView getDatePicker() { return _monthPicker; } void tryNotifyDateSet() { if (_callBack != null) { _monthPicker.clearFocus(); _callBack.onDateSet(_monthPicker.getMonth(), _monthPicker.getYear()); } } @Override protected void onStop() { super.onStop(); } private void setMinMonth(int minMonth) { _monthPicker.setMinMonth(minMonth); } private void setMaxMonth(int maxMonth) { _monthPicker.setMaxMonth(maxMonth); } private void setMinYear(int minYear) { _monthPicker.setMinYear(minYear); } private void setMaxYear(int maxYear) { _monthPicker.setMaxYear(maxYear); } private void setActivatedMonth(int activatedMonth) { _monthPicker.setActivatedMonth(activatedMonth); } private void setActivatedYear(int activatedMonth) { _monthPicker.setActivatedYear(activatedMonth); } private void setMonthPickerTitle(String title) { _monthPicker.setTitle(title); } private void showMonthOnly() { _monthPicker.showMonthOnly(); } private void showYearOnly() { _monthPicker.showYearOnly(); } private void setOnMonthChangedListener(OnMonthChangedListener onMonthChangedListener) { if (onMonthChangedListener != null) { _monthPicker.setOnMonthChangedListener(onMonthChangedListener); } } private void setOnYearChangedListener(OnYearChangedListener onYearChangedListener) { if (onYearChangedListener != null) { _monthPicker.setOnYearChangedListener(onYearChangedListener); } } public static class Builder { private static final String TAG = MonthPickerDialog.Builder.class.getName(); private Context _context; private OnDateSetListener _callBack; private int _activatedMonth, _activatedYear; private int _minMonth = Calendar.JANUARY, _maxMonth = Calendar.DECEMBER; private int _minYear, _maxYear; private boolean monthOnly, yearOnly; private String title = null; private MonthPickerDialog monthPickerDialog; private OnYearChangedListener _onYearChanged; private OnMonthChangedListener _onMonthChanged; /** * Build a Dialog with month and year with given context. * * @param context Context: the parent context * @param callBack MonthPickerDialog.OnDateSetListener: the listener to call * when the user sets the date * @param year the initially selected year * @param month the initially selected month (0-11 for compatibility with * {@link Calendar}Calender.MONTH or Calendar.JANUARY, Calendar.FEBRUARY etc) */ public Builder(Context context, OnDateSetListener callBack, int year, @IntRange(from = Calendar.JANUARY, to = Calendar.DECEMBER) int month) { if (month >= Calendar.JANUARY && month <= Calendar.DECEMBER) { this._activatedMonth = month; } else { throw new IllegalArgumentException("Month range should be between 0 " + "(Calender.JANUARY) to 11 (Calendar.DECEMBER)"); } if (year >= 1) { this._activatedYear = year; } else { throw new IllegalArgumentException("Selected year should be > 1"); } this._context = context; this._callBack = callBack; if (year > MonthPickerView._minYear) { _minYear = MonthPickerView._minYear; } else { _minYear = year; MonthPickerView._minYear = year; } if (year > MonthPickerView._maxYear) { _maxYear = year; MonthPickerView._maxYear = year; } else { _maxYear = MonthPickerView._maxYear; } } /** * Minimum enable month in picker (0-11 for compatibility with Calender.MONTH or * Calendar.JANUARY, Calendar.FEBRUARY etc). * * @param minMonth * @return Builder */ public Builder setMinMonth(@IntRange(from = Calendar.JANUARY, to = Calendar.DECEMBER) int minMonth) { if (minMonth >= Calendar.JANUARY && minMonth <= Calendar.DECEMBER) { this._minMonth = minMonth; return this; } else { throw new IllegalArgumentException("Month range should be between 0 " + "(Calender.JANUARY) to 11 (Calendar.DECEMBER)"); } } /** * Maximum enabled month in picker (0-11 for compatibility with Calender.MONTH or * Calendar.JANUARY, Calendar.FEBRUARY etc). * * @param maxMonth * @return */ public Builder setMaxMonth(@IntRange(from = Calendar.JANUARY, to = Calendar.DECEMBER) int maxMonth) { /* if (maxMonth >= Calendar.JANUARY && maxMonth <= Calendar.DECEMBER) {*/ this._maxMonth = maxMonth; return this; /*} else { throw new IllegalArgumentException("Month range should be between 0 " + "(Calender.JANUARY) to 11 (Calendar.DECEMBER)"); }*/ } /** * Starting year in the picker. * * @param minYear * @return Builder */ public Builder setMinYear(int minYear) { this._minYear = minYear; return this; } /** * Ending year in the picker. * * @param maxYear * @return Builder */ public Builder setMaxYear(int maxYear) { this._maxYear = maxYear; return this; } /** * Initially selected month (0-11 for compatibility with Calender.MONTH or * Calendar.JANUARY, Calendar.FEBRUARY etc). * * @param activatedMonth * @return Builder */ public Builder setActivatedMonth(@IntRange(from = Calendar.JANUARY, to = Calendar.DECEMBER) int activatedMonth) { this._activatedMonth = activatedMonth; return this; } /** * Initially selected year (0-11 for compatibility with Calender.MONTH or * Calendar.JANUARY, Calendar.FEBRUARY etc). * * @param activatedYear * @return Builder */ public Builder setActivatedYear(int activatedYear) { this._activatedYear = activatedYear; return this; } /** * Minimum and Maximum enable month in picker (0-11 for compatibility with Calender.MONTH or * Calendar.JANUARY, Calendar.FEBRUARY etc). * * @param minMonth minimum enabled month. * @param maxMonth maximum enabled month. * @return Builder */ public Builder setMonthRange(@IntRange(from = Calendar.JANUARY, to = Calendar.DECEMBER) int minMonth, @IntRange(from = Calendar.JANUARY, to = Calendar.DECEMBER) int maxMonth) { if (minMonth >= Calendar.JANUARY && minMonth <= Calendar.DECEMBER && maxMonth >= Calendar.JANUARY && maxMonth <= Calendar.DECEMBER) { this._minMonth = minMonth; this._maxMonth = maxMonth; return this; } else { throw new IllegalArgumentException("Month range should be between 0 " + "(Calender.JANUARY) to 11 (Calendar.DECEMBER)"); } } /** * Starting and ending year show in picker * * @param minYear starting year * @param maxYear ending year * @return */ public Builder setYearRange(int minYear, int maxYear) { if (minYear <= maxYear) { this._minYear = minYear; this._maxYear = maxYear; return this; } else { throw new IllegalArgumentException("Minimum year should be less then Maximum year"); } } /** * Set the Minimum, maximum enabled months and starting , ending years. * * @param minMonth minimum enabled month in picker * @param maxMonth maximum enabled month in picker * @param minYear starting year * @param maxYear ending year * @return */ public Builder setMonthAndYearRange(@IntRange(from = Calendar.JANUARY, to = Calendar.DECEMBER) int minMonth, @IntRange(from = Calendar.JANUARY, to = Calendar.DECEMBER) int maxMonth, int minYear, int maxYear) { if (minMonth >= Calendar.JANUARY && minMonth <= Calendar.DECEMBER && maxMonth >= Calendar.JANUARY && maxMonth <= Calendar.DECEMBER) { this._minMonth = minMonth; this._maxMonth = maxMonth; } else { throw new IllegalArgumentException("Month range should be between 0 " + "(Calender.JANUARY) to 11 (Calendar.DECEMBER)"); } if (minYear <= maxYear) { this._minYear = minYear; this._maxYear = maxYear; } else { throw new IllegalArgumentException("Minimum year should be less then Maximum year"); } return this; } /** * User can select month only. Year won't be shown to user once user select the month. * * @return Builder */ public Builder showMonthOnly() { if (yearOnly) { Log.e(TAG, "yearOnly also set to true before. Now setting yearOnly to false" + " monthOnly to true"); } this.yearOnly = false; this.monthOnly = true; return this; } /** * User can select year only. Month won't be shown to user once user select the month. * * @return Builder */ public Builder showYearOnly() { if (monthOnly) { Log.e(TAG, "monthOnly also set to true before. Now setting monthOnly to " + "false and yearOnly to true"); } this.monthOnly = false; this.yearOnly = true; return this; } /** * Set the title to the picker. * * @param title * @return Builder */ public Builder setTitle(String title) { this.title = title; return this; } /** * Sets the callback that will be called when user click on any month. * * @param onMonthChangedListener * @return Builder */ public Builder setOnMonthChangedListener(OnMonthChangedListener onMonthChangedListener) { this._onMonthChanged = onMonthChangedListener; return this; } /** * Sets the callback that will be called when the user select any year. * * @param onYearChangedListener * @return Builder */ public Builder setOnYearChangedListener(OnYearChangedListener onYearChangedListener) { this._onYearChanged = onYearChangedListener; return this; } public MonthPickerDialog build() { if (_minMonth > _maxMonth) { throw new IllegalArgumentException("Minimum month should always " + "smaller then maximum month."); } if (_minYear > _maxYear) { throw new IllegalArgumentException("Minimum year should always " + "smaller then maximum year."); } if (_activatedMonth < _minMonth || _activatedMonth > _maxMonth) { throw new IllegalArgumentException("Activated month should always " + "in between Minimum and maximum month."); } if (_activatedYear < _minYear || _activatedYear > _maxYear) { throw new IllegalArgumentException("Activated year should always " + "in between Minimum year and maximum year."); } monthPickerDialog = new MonthPickerDialog(_context, _callBack, _activatedYear, _activatedMonth); if (monthOnly) { monthPickerDialog.showMonthOnly(); _minYear = 0; _maxYear = 0; _activatedYear = 0; } else if (yearOnly) { monthPickerDialog.showYearOnly(); _minMonth = 0; _maxMonth = 0; _activatedMonth = 0; } monthPickerDialog.setMinMonth(_minMonth); monthPickerDialog.setMaxMonth(_maxMonth); monthPickerDialog.setMinYear(_minYear); monthPickerDialog.setMaxYear(_maxYear); monthPickerDialog.setActivatedMonth(_activatedMonth); monthPickerDialog.setActivatedYear(_activatedYear); if (_onMonthChanged != null) { monthPickerDialog.setOnMonthChangedListener(_onMonthChanged); } if (_onYearChanged != null) { monthPickerDialog.setOnYearChangedListener(_onYearChanged); } if (title != null) { monthPickerDialog.setMonthPickerTitle(title.trim()); } return monthPickerDialog; } } /** * The callback used to indicate the user is done selecting month. */ public interface OnDateSetListener { /** * @param selectedMonth The month that was set (0-11) for compatibility with {@link Calendar}. * @param selectedYear The year that was set. */ void onDateSet(int selectedMonth, int selectedYear); } /** * The callback used to indicate the user click on month */ public interface OnMonthChangedListener { /** * @param selectedMonth The month that was set (0-11) for compatibility * with {@link Calendar}. */ void onMonthChanged(int selectedMonth); } /** * The callback used to indicate the user click on year. */ public interface OnYearChangedListener { /** * Called upon a year change. * * @param year The year that was set. */ void onYearChanged(int year); } public interface OnConfigChangeListener{ void onConfigChange(); } } ================================================ FILE: monthandyearpicker/src/main/java/com/whiteelephant/monthpicker/MonthPickerView.java ================================================ package com.whiteelephant.monthpicker; import android.content.Context; import android.content.res.Configuration; import android.content.res.TypedArray; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.example.prem.firstpitch.R; import java.text.DateFormatSymbols; import java.util.Calendar; import java.util.HashMap; import java.util.Locale; class MonthPickerView extends FrameLayout { YearPickerView _yearView; ListView _monthList; static int _minYear = 1900, _maxYear = Calendar.getInstance().get(Calendar.YEAR); MonthViewAdapter _monthViewAdapter; TextView _month, _year, _title; Context _context; int _headerFontColorSelected, _headerFontColorNormal; boolean _showMonthOnly; int _selectedMonth, _selectedYear; MonthPickerDialog.OnYearChangedListener _onYearChanged; MonthPickerDialog.OnMonthChangedListener _onMonthChanged; OnDateSet _onDateSet; OnCancel _onCancel; private String[] _monthNames; /*private static final int[] ATTRS_TEXT_COLOR = new int[] { com.android.internal.R.attr.textColor}; private static final int[] ATTRS_DISABLED_ALPHA = new int[] { com.android.internal.R.attr.disabledAlpha};*/ public MonthPickerView(Context context) { this(context, null); _context = context; } public MonthPickerView(Context context, AttributeSet attrs) { this(context, attrs, 0); _context = context; } public MonthPickerView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); _context = context; LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mInflater.inflate(R.layout.month_picker_view, this); _monthNames = new DateFormatSymbols(Locale.getDefault()).getShortMonths(); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.monthPickerDialog, defStyleAttr, 0); // getting default values based on the user's theme. /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { headerBgColor = android.R.attr.colorAccent; } else { //Get colorAccent defined for AppCompat headerBgColor = context.getResources().getIdentifier("colorAccent", "attr", context.getPackageName()); } TypedValue outValue = new TypedValue(); context.getTheme().resolveAttribute(headerBgColor, outValue, true); int color = outValue.data; // OR TypedValue typedValue = new TypedValue(); TypedArray a = mContext.obtainStyledAttributes(typedValue.data, new int[] { R.attr.colorAccent, R.attr.colorPrimary }); int color = a.getColor(0, 0); a.recycle(); // OR final TypedValue value = new TypedValue (); context.getTheme ().resolveAttribute (R.attr.colorAccent, value, true); int color = value.data */ int headerBgColor = a.getColor(R.styleable.monthPickerDialog_headerBgColor, 0); _headerFontColorNormal = a.getColor(R.styleable.monthPickerDialog_headerFontColorNormal, 0); _headerFontColorSelected = a.getColor(R.styleable.monthPickerDialog_headerFontColorSelected, 0); int monthBgColor = a.getColor(R.styleable.monthPickerDialog_monthBgColor, 0); int monthBgSelectedColor = a.getColor(R.styleable.monthPickerDialog_monthBgSelectedColor, 0); int monthFontColorNormal = a.getColor(R.styleable.monthPickerDialog_monthFontColorNormal, 0); int monthFontColorSelected = a.getColor(R.styleable.monthPickerDialog_monthFontColorSelected, 0); int monthFontColorDisabled = a.getColor(R.styleable.monthPickerDialog_monthFontColorDisabled, 0); int headerTitleColor = a.getColor(R.styleable.monthPickerDialog_headerTitleColor, 0); int actionButtonColor = a.getColor(R.styleable.monthPickerDialog_dialogActionButtonColor, 0); if (monthFontColorNormal == 0) { monthFontColorNormal = getResources().getColor(R.color.fontBlackEnable); /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { monthFontColorNormal = android.R.attr.textColor; } else { monthFontColorNormal = getResources().getIdentifier("textColor", "attr", null); } TypedValue outValue = new TypedValue(); context.getTheme().resolveAttribute(monthFontColorNormal, outValue, true); int color = outValue.data; monthFontColorNormal = color;*/ /*monthFontColorNormal = context.getTheme().resolveAttribute( android.R.attr.textColorPrimary, outValue, true) ? outValue.data : getResources().getColor(R.color.fontBlackEnable);*/ } if (monthFontColorSelected == 0) { monthFontColorSelected = getResources().getColor(R.color.fontWhiteEnable); } if (monthFontColorDisabled == 0) { monthFontColorDisabled = getResources().getColor(R.color.fontBlackDisable); } if (_headerFontColorNormal == 0) { _headerFontColorNormal = getResources().getColor(R.color.fontWhiteDisable); } if (_headerFontColorSelected == 0) { _headerFontColorSelected = getResources().getColor(R.color.fontWhiteEnable); } if (headerTitleColor == 0) { headerTitleColor = getResources().getColor(R.color.fontWhiteEnable); } if (monthBgColor == 0) { monthBgColor = getResources().getColor(R.color.fontWhiteEnable); } if (headerBgColor == 0) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { headerBgColor = android.R.attr.colorAccent; } else { //Get colorAccent defined for AppCompat headerBgColor = context.getResources().getIdentifier("colorAccent", "attr", context.getPackageName()); } TypedValue outValue = new TypedValue(); context.getTheme().resolveAttribute(headerBgColor, outValue, true); headerBgColor = outValue.data; } if (monthBgSelectedColor == 0) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { monthBgSelectedColor = android.R.attr.colorAccent; } else { //Get colorAccent defined for AppCompat monthBgSelectedColor = context.getResources().getIdentifier("colorAccent", "attr", context.getPackageName()); } TypedValue outValue = new TypedValue(); context.getTheme().resolveAttribute(monthBgSelectedColor, outValue, true); monthBgSelectedColor = outValue.data; } HashMap map = new HashMap(); if (monthBgColor != 0) map.put("monthBgColor", monthBgColor); if (monthBgSelectedColor != 0) map.put("monthBgSelectedColor", monthBgSelectedColor); if (monthFontColorNormal != 0) map.put("monthFontColorNormal", monthFontColorNormal); if (monthFontColorSelected != 0) map.put("monthFontColorSelected", monthFontColorSelected); if (monthFontColorDisabled != 0) map.put("monthFontColorDisabled", monthFontColorDisabled); a.recycle(); _monthList = (ListView) findViewById(R.id.listview); _yearView = (YearPickerView) findViewById(R.id.yearView); _month = (TextView) findViewById(R.id.month); _year = (TextView) findViewById(R.id.year); _title = (TextView) findViewById(R.id.title); RelativeLayout _pickerBg = (RelativeLayout) findViewById(R.id.picker_view); LinearLayout _header = (LinearLayout) findViewById(R.id.header); RelativeLayout _actionBtnLay = (RelativeLayout) findViewById(R.id.action_btn_lay); TextView ok = (TextView) findViewById(R.id.ok_action); TextView cancel = (TextView) findViewById(R.id.cancel_action); if (actionButtonColor != 0) { ok.setTextColor(actionButtonColor); cancel.setTextColor(actionButtonColor); } else { ok.setTextColor(headerBgColor); cancel.setTextColor(headerBgColor); } if (_headerFontColorSelected != 0) _month.setTextColor(_headerFontColorSelected); if (_headerFontColorNormal != 0) _year.setTextColor(_headerFontColorNormal); if (headerTitleColor != 0) _title.setTextColor(headerTitleColor); if (headerBgColor != 0) _header.setBackgroundColor(headerBgColor); if (monthBgColor != 0) _pickerBg.setBackgroundColor(monthBgColor); if(monthBgColor != 0) _actionBtnLay.setBackgroundColor(monthBgColor); ok.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { _onDateSet.onDateSet(); } }); cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { _onCancel.onCancel(); } }); _monthViewAdapter = new MonthViewAdapter(context); _monthViewAdapter.setColors(map); _monthViewAdapter.setOnDaySelectedListener(new MonthViewAdapter.OnDaySelectedListener() { @Override public void onDaySelected(MonthViewAdapter view, int selectedMonth) { Log.d("----------------", "MonthPickerDialogStyle selected month = " + selectedMonth); MonthPickerView.this._selectedMonth = selectedMonth; _month.setText(_monthNames[selectedMonth]); if (!_showMonthOnly) { _monthList.setVisibility(View.GONE); _yearView.setVisibility(View.VISIBLE); _month.setTextColor(_headerFontColorNormal); _year.setTextColor(_headerFontColorSelected); } if (_onMonthChanged != null) { _onMonthChanged.onMonthChanged(selectedMonth); } } }); _monthList.setAdapter(_monthViewAdapter); _yearView.setRange(_minYear, _maxYear); _yearView.setColors(map); _yearView.setYear(Calendar.getInstance().get(Calendar.YEAR)); _yearView.setOnYearSelectedListener(new YearPickerView.OnYearSelectedListener() { @Override public void onYearChanged(YearPickerView view, int selectedYear) { Log.d("----------------", "selected year = " + selectedYear); MonthPickerView.this._selectedYear = selectedYear; _year.setText("" + selectedYear); _year.setTextColor(_headerFontColorSelected); _month.setTextColor(_headerFontColorNormal); if (_onYearChanged != null) { _onYearChanged.onYearChanged(selectedYear); } } }); _month.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (_monthList.getVisibility() == GONE) { _yearView.setVisibility(GONE); _monthList.setVisibility(VISIBLE); _year.setTextColor(_headerFontColorNormal); _month.setTextColor(_headerFontColorSelected); } } }); _year.setOnClickListener(new OnClickListener(){ @Override public void onClick(View view) { if (_yearView.getVisibility() == GONE) { _monthList.setVisibility(GONE); _yearView.setVisibility(VISIBLE); _year.setTextColor(_headerFontColorSelected); _month.setTextColor(_headerFontColorNormal); } } }); } protected void init(int year, int month) { _selectedYear = year; _selectedMonth = month; } protected void setMaxMonth(int maxMonth) { if (maxMonth <= Calendar.DECEMBER && maxMonth >= Calendar.JANUARY) { _monthViewAdapter.setMaxMonth(maxMonth); } else { throw new IllegalArgumentException("Month out of range please send months between " + "Calendar.JANUARY, Calendar.DECEMBER"); } } protected void setMinMonth(int minMonth) { if (minMonth >= Calendar.JANUARY && minMonth <= Calendar.DECEMBER) { _monthViewAdapter.setMinMonth(minMonth); } else { throw new IllegalArgumentException("Month out of range please send months between" + " Calendar.JANUARY, Calendar.DECEMBER"); } } protected void setMinYear(int minYear) { _yearView.setMinYear(minYear); } protected void setMaxYear(int maxYear) { _yearView.setMaxYear(maxYear); } protected void showMonthOnly() { _showMonthOnly = true; _year.setVisibility(GONE); } protected void showYearOnly() { _monthList.setVisibility(View.GONE); _yearView.setVisibility(VISIBLE); _month.setVisibility(GONE); _year.setTextColor(_headerFontColorSelected); } protected void setActivatedMonth(int activatedMonth) { if (activatedMonth >= Calendar.JANUARY && activatedMonth <= Calendar.DECEMBER) { _monthViewAdapter.setActivatedMonth(activatedMonth); _month.setText(_monthNames[activatedMonth]); } else { throw new IllegalArgumentException("Month out of range please send months between Calendar.JANUARY, Calendar.DECEMBER"); } } protected void setActivatedYear(int activatedYear) { _yearView.setActivatedYear(activatedYear); _year.setText(Integer.toString(activatedYear)); } protected void setMonthRange(int minMonth, int maxMonth) { if (minMonth < maxMonth) { setMinMonth(minMonth); setMaxYear(maxMonth); } else { throw new IllegalArgumentException("maximum month is less then minimum month"); } } protected void setYearRange(int minYear, int maxYear) { if (minYear < maxYear) { setMinYear(minYear); setMaxYear(maxYear); } else { throw new IllegalArgumentException("maximum year is less then minimum year"); } } protected void setMonthYearRange(int minMonth, int maxMonth, int minYear, int maxYear) { setMonthRange(minMonth, maxMonth); setYearRange(minYear, maxYear); } protected void setTitle(String dialogTitle) { if (dialogTitle != null && dialogTitle.trim().length() > 0) { _title.setText(dialogTitle); _title.setVisibility(VISIBLE); } else { _title.setVisibility(GONE); } } protected int getMonth() { return _selectedMonth; } protected int getYear() { return _selectedYear; } protected void setOnMonthChangedListener(MonthPickerDialog.OnMonthChangedListener onMonthChangedListener) { if (onMonthChangedListener != null) { this._onMonthChanged = onMonthChangedListener; } } protected void setOnYearChangedListener(MonthPickerDialog.OnYearChangedListener onYearChangedListener) { if (onYearChangedListener != null) { this._onYearChanged = onYearChangedListener; } } public void setOnDateListener(OnDateSet onDateSet) { this._onDateSet = onDateSet; } public void setOnCancelListener(OnCancel onCancel) { this._onCancel = onCancel; } public interface OnDateSet{ void onDateSet(); } public interface OnCancel{ void onCancel(); } MonthPickerDialog.OnConfigChangeListener configChangeListener; protected void setOnConfigurationChanged(MonthPickerDialog.OnConfigChangeListener configChangeListener){ this.configChangeListener = configChangeListener; } @Override protected void onConfigurationChanged(Configuration newConfig) { configChangeListener.onConfigChange(); super.onConfigurationChanged(newConfig); } } ================================================ FILE: monthandyearpicker/src/main/java/com/whiteelephant/monthpicker/MonthView.java ================================================ package com.whiteelephant.monthpicker; import android.content.Context; import android.content.res.Configuration; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.MotionEvent; import android.widget.ListView; import com.example.prem.firstpitch.R; import java.text.DateFormatSymbols; import java.util.HashMap; import java.util.Locale; class MonthView extends ListView { // constants private static final int DEFAULT_HEIGHT = 100; private static final int DEFAULT_NUM_DAYS = 4; private static final int DEFAULT_NUM_ROWS = 3; private static final int MAX_NUM_ROWS = 3; private static final int DAY_SEPARATOR_WIDTH = 1; // days to display private int _numDays = DEFAULT_NUM_DAYS; private int _numCells = _numDays; private int _numRows = DEFAULT_NUM_ROWS; // layout padding private int _padding = 40; private int _width; private int _rowHeight = DEFAULT_HEIGHT; // paints private Paint _monthNumberPaint; private Paint _monthNumberDisabledPaint; private Paint _monthNumberSelectedPaint; // month private String[] _monthNames; private int _monthTextSize; private int _monthHeaderSize; private int _monthSelectedCircleSize; private int _monthBgSelectedColor; private int _monthFontColorNormal; private int _monthFontColorSelected; private int _monthFontColorDisabled; private int _maxMonth, _minMonth; private int _rowHeightKey; private int _selectedMonth = -1; // listener private OnMonthClickListener _onMonthClickListener; public MonthView(Context context) { this(context, null); } public MonthView(Context context, AttributeSet attrs) { this(context, attrs, R.style.MonthPickerDialogStyle); } public MonthView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); _monthNames = new DateFormatSymbols(Locale.getDefault()).getShortMonths(); DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); _monthTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, displayMetrics); _monthHeaderSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, displayMetrics); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { _monthSelectedCircleSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 43, displayMetrics); } else { _monthSelectedCircleSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 43, displayMetrics); } _rowHeightKey = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 250, displayMetrics); _rowHeight = (_rowHeightKey - _monthHeaderSize) / MAX_NUM_ROWS; _padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, displayMetrics); } /** * Sets up the text and style properties for painting. */ private void initView() { _monthNumberSelectedPaint = new Paint(); _monthNumberSelectedPaint.setAntiAlias(true); if (_monthBgSelectedColor != 0) _monthNumberSelectedPaint.setColor(_monthBgSelectedColor); // _monthNumberSelectedPaint.setAlpha(200); _monthNumberSelectedPaint.setTextAlign(Paint.Align.CENTER); _monthNumberSelectedPaint.setStyle(Paint.Style.FILL); _monthNumberSelectedPaint.setFakeBoldText(true); _monthNumberPaint = new Paint(); _monthNumberPaint.setAntiAlias(true); if (_monthFontColorNormal != 0) _monthNumberPaint.setColor(_monthFontColorNormal); _monthNumberPaint.setTextSize(_monthTextSize); _monthNumberPaint.setTextAlign(Paint.Align.CENTER); _monthNumberPaint.setStyle(Paint.Style.FILL); _monthNumberPaint.setFakeBoldText(false); _monthNumberDisabledPaint = new Paint(); _monthNumberDisabledPaint.setAntiAlias(true); if (_monthFontColorDisabled != 0) _monthNumberDisabledPaint.setColor(_monthFontColorDisabled); _monthNumberDisabledPaint.setTextSize(_monthTextSize); _monthNumberDisabledPaint.setTextAlign(Paint.Align.CENTER); _monthNumberDisabledPaint.setStyle(Paint.Style.FILL); _monthNumberDisabledPaint.setFakeBoldText(false); } @Override protected void onDraw(Canvas canvas) { drawDays(canvas); } /** * Draws the month days. */ private void drawDays(Canvas canvas) { int y = (((_rowHeight + _monthTextSize) / 2) - DAY_SEPARATOR_WIDTH) + _monthHeaderSize; int dayWidthHalf = (_width - _padding * 2) / (_numDays * 2); int j = 0; for (int month = 0; month < _monthNames.length; month++) { int x = (2 * j + 1) * dayWidthHalf + _padding; if (_selectedMonth == month) { canvas.drawCircle(x, y - (_monthTextSize / 3), _monthSelectedCircleSize, _monthNumberSelectedPaint); if (_monthFontColorSelected != 0) _monthNumberPaint.setColor(_monthFontColorSelected); } else { if (_monthFontColorNormal != 0) _monthNumberPaint.setColor(_monthFontColorNormal); } final Paint paint = (month < _minMonth || month > _maxMonth) ? _monthNumberDisabledPaint : _monthNumberPaint; canvas.drawText(_monthNames[month], x, y, paint); j++; if (j == _numDays) { j = 0; y += _rowHeight; } } } /** * Calculates the day that the given x position is in, accounting for week * number. Returns the day or -1 if the position wasn't in a day. * * @param x The x position of the touch event * @return The day number, or -1 if the position wasn't in a day */ private int getMonthFromLocation(float x, float y) { int dayStart = _padding; if (x < dayStart || x > _width - _padding) { return -1; } // Selection is (x - start) / (pixels/day) == (x -s) * day / pixels int row = (int) (y - _monthHeaderSize) / _rowHeight; int column = (int) ((x - dayStart) * _numDays / (_width - dayStart - _padding)); int day = column + 1; day += row * _numDays; if (day < 0 || day > _numCells) { return -1; } // position - 1 to match with Calender.JANUARY and Calender.DECEMBER return day - 1; } /** * Called when the user clicks on a day. Handles callbacks to the * {@link OnMonthClickListener} if one is set. * * @param day The day that was clicked */ private void onDayClick(int day) { if (_onMonthClickListener != null) { _onMonthClickListener.onMonthClick(this, day); } } protected void setColors(HashMap colors) { if (colors.containsKey("monthBgSelectedColor") ) _monthBgSelectedColor = colors.get("monthBgSelectedColor"); if (colors.containsKey("monthFontColorNormal")) _monthFontColorNormal = colors.get("monthFontColorNormal"); if (colors.containsKey("monthFontColorSelected")) _monthFontColorSelected = colors.get("monthFontColorSelected"); if (colors.containsKey("monthFontColorDisabled")) _monthFontColorDisabled = colors.get("monthFontColorDisabled"); initView(); } /** * Handles callbacks when the user clicks on a time object. */ public interface OnMonthClickListener { void onMonthClick(MonthView view, int month); } public void setOnMonthClickListener(OnMonthClickListener listener) { _onMonthClickListener = listener; } void setMonthParams(int selectedMonth, int minMonth, int maxMonth) { _selectedMonth = selectedMonth; this._minMonth = minMonth; this._maxMonth = maxMonth; _numCells = 12; } public void reuse() { _numRows = DEFAULT_NUM_ROWS; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), _rowHeight * _numRows + (_monthHeaderSize * 2)); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { _width = w; } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_UP: int day = getMonthFromLocation(event.getX(), event.getY()); if (day >= 0) { onDayClick(day); } break; } return true; } } ================================================ FILE: monthandyearpicker/src/main/java/com/whiteelephant/monthpicker/MonthViewAdapter.java ================================================ package com.whiteelephant.monthpicker; import android.content.Context; import android.os.Build; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import com.example.prem.firstpitch.R; import java.util.Calendar; import java.util.HashMap; class MonthViewAdapter extends BaseAdapter { private int _minMonth, _maxMonth, _activatedMonth; private Context _context; private HashMap _colors; private OnDaySelectedListener mOnDaySelectedListener; public MonthViewAdapter(Context context) { this._context = context; setRange(); } @Override public int getCount() { return 1; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup viewGroup) { final MonthView v; if (convertView != null) { v = (MonthView) convertView; } else { v = new MonthView(_context); v.setColors(_colors); // Set up the new view final AbsListView.LayoutParams params = new AbsListView.LayoutParams( AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.MATCH_PARENT); v.setLayoutParams(params); v.setClickable(true); v.setOnMonthClickListener(mOnDayClickListener); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // If we're running on Honeycomb or newer, then we can use the Theme's // selectableItemBackground to ensure that the View has a pressed state v.setBackgroundDrawable(_context.getDrawable(R.drawable.month_ripplr)); } v.setMonthParams(_activatedMonth, _minMonth, _maxMonth); v.reuse(); v.invalidate(); return v; } private final MonthView.OnMonthClickListener mOnDayClickListener = new MonthView.OnMonthClickListener() { @Override public void onMonthClick(MonthView view, int day) { Log.d("MonthViewAdapter", "onDayClick " + day); if (isCalendarInRange(day)) { Log.d("MonthViewAdapter", "day not null && Calender in range " + day); setSelectedMonth(day); if (mOnDaySelectedListener != null) { mOnDaySelectedListener.onDaySelected(MonthViewAdapter.this, day); } } } }; boolean isCalendarInRange(int value) { return value >= _minMonth && value <= _maxMonth; } /** * Updates the selected day and related parameters. * * @param month The day to highlight */ public void setSelectedMonth(int month) { Log.d("MonthViewAdapter", "setSelectedMonth : " + month); _activatedMonth = month; notifyDataSetChanged(); } /* set min and max date and years*/ public void setRange() { _minMonth = Calendar.JANUARY; _maxMonth = Calendar.DECEMBER; _activatedMonth = Calendar.AUGUST; notifyDataSetInvalidated(); } /** * Sets the listener to call when the user selects a day. * * @param listener The listener to call. */ public void setOnDaySelectedListener(OnDaySelectedListener listener) { mOnDaySelectedListener = listener; } public interface OnDaySelectedListener { void onDaySelected(MonthViewAdapter view, int month); } void setMaxMonth(int maxMonth) { if (maxMonth <= Calendar.DECEMBER && maxMonth >= Calendar.JANUARY) { _maxMonth = maxMonth; } else { throw new IllegalArgumentException("Month out of range please send months between Calendar.JANUARY, Calendar.DECEMBER"); } } void setMinMonth(int minMonth) { if (minMonth >= Calendar.JANUARY && minMonth <= Calendar.DECEMBER) { _minMonth = minMonth; } else { throw new IllegalArgumentException("Month out of range please send months between Calendar.JANUARY, Calendar.DECEMBER"); } } void setActivatedMonth(int activatedMonth) { if (activatedMonth >= Calendar.JANUARY && activatedMonth <= Calendar.DECEMBER) { _activatedMonth = activatedMonth; } else { throw new IllegalArgumentException("Month out of range please send months between Calendar.JANUARY, Calendar.DECEMBER"); } } void setColors(HashMap map) { _colors = map; } } ================================================ FILE: monthandyearpicker/src/main/java/com/whiteelephant/monthpicker/YearPickerView.java ================================================ package com.whiteelephant.monthpicker; import android.content.Context; import android.content.res.Resources; import android.support.annotation.DrawableRes; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import com.example.prem.firstpitch.R; import java.util.HashMap; class YearPickerView extends ListView { private Context _context; final YearAdapter _adapter; final int _viewSize; final int _childSize; OnYearSelectedListener _onYearSelectedListener; HashMap _colors; public YearPickerView(Context context) { this(context, null); } public YearPickerView(Context context, AttributeSet attrs) { this(context, attrs, R.style.AppTheme); super.setSelector(android.R.color.transparent); } public YearPickerView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this._context = context; final LayoutParams frame = new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); setLayoutParams(frame); final Resources res = context.getResources(); _viewSize = res.getDimensionPixelOffset(R.dimen.datepicker_view_animator_height); _childSize = res.getDimensionPixelOffset(R.dimen.datepicker_year_label_height); setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { final int year = _adapter.getYearForPosition(position); _adapter.setSelection(year); if (_onYearSelectedListener != null) { _onYearSelectedListener.onYearChanged(YearPickerView.this, year); } } }); _adapter = new YearAdapter(getContext()); setAdapter(_adapter); } public void setOnYearSelectedListener(OnYearSelectedListener listener) { _onYearSelectedListener = listener; } /** * Sets the currently selected year. Jumps immediately to the new year. * * @param year the target year */ public void setYear(final int year) { _adapter.setSelection(year); post(new Runnable() { @Override public void run() { final int position = _adapter.getPositionForYear(year); if (position >= 0 /*&& position < getCount()*/) { setSelectionCentered(position); } } }); } public void setSelectionCentered(int position) { final int offset = _viewSize / 2 - _childSize / 2; setSelectionFromTop(position, offset); } public void setRange(int min, int max) { _adapter.setRange(min, max); } public void setColors(HashMap colors) { this._colors = colors; } private class YearAdapter extends BaseAdapter { private final int ITEM_LAYOUT = R.layout.year_label_text_view; private final LayoutInflater __inflater; private int __activatedYear; private int __minYear, __maxYear, __count; public YearAdapter(Context context) { __inflater = LayoutInflater.from(context); } public void setRange(int min, int max) { int count = max - min + 1; if (__minYear != min || __maxYear != max || __count != count) { __minYear = min; __maxYear = max; __count = count; notifyDataSetInvalidated(); } } public boolean setSelection(int year) { if (__activatedYear != year) { __activatedYear = year; notifyDataSetChanged(); return true; } return false; } @Override public int getCount() { return __count; } @Override public Integer getItem(int position) { return getYearForPosition(position); } @Override public long getItemId(int position) { return getYearForPosition(position); } public int getPositionForYear(int year) { return year - __minYear; } public int getYearForPosition(int position) { return __minYear + position; } @Override public boolean hasStableIds() { return true; } @Override public View getView(int position, View convertView, ViewGroup parent) { final TextView v; final boolean hasNewView = convertView == null; if (hasNewView) { v = (TextView) __inflater.inflate(ITEM_LAYOUT, parent, false); } else { v = (TextView) convertView; } final int year = getYearForPosition(position); final boolean activated = __activatedYear == year; if (hasNewView || v.getTag() != null || v.getTag().equals(activated)) { if (activated) { if(_colors.containsKey("monthBgSelectedColor")) { v.setTextColor(_colors.get("monthBgSelectedColor")); } v.setTextSize(25); } else { if(_colors.containsKey("monthFontColorNormal")) { v.setTextColor(_colors.get("monthFontColorNormal")); } v.setTextSize(20); } v.setTag(activated); } v.setText(Integer.toString(year)); return v; } @Override public int getItemViewType(int position) { return 0; } @Override public int getViewTypeCount() { return 1; } @Override public boolean isEmpty() { return false; } @Override public boolean areAllItemsEnabled() { return true; } @Override public boolean isEnabled(int position) { return true; } protected void setMaxYear(int maxYear) { __maxYear = maxYear; __count = __maxYear - __minYear + 1; notifyDataSetInvalidated(); } protected void setMinYear(int minYear) { __minYear = minYear; __count = __maxYear - __minYear + 1; notifyDataSetInvalidated(); } protected void setActivatedYear(int activatedYear) { if (activatedYear >= __minYear && activatedYear <= __maxYear) { __activatedYear = activatedYear; setYear(activatedYear); } else { throw new IllegalArgumentException("activated date is not in range"); } } } public int getFirstPositionOffset() { final View firstChild = getChildAt(0); if (firstChild == null) { return 0; } return firstChild.getTop(); } /** * The callback used to indicate the user changed the year. */ public interface OnYearSelectedListener { /** * Called upon a year change. * * @param view The view associated with this listener. * @param year The year that was set. */ void onYearChanged(YearPickerView view, int year); } protected void setMinYear(int minYear) { _adapter.setMinYear(minYear); } protected void setMaxYear(int maxYear) { _adapter.setMaxYear(maxYear); } protected void setActivatedYear(int activatedYear) { _adapter.setActivatedYear(activatedYear); } } ================================================ FILE: monthandyearpicker/src/main/res/drawable-v21/month_ripplr.xml ================================================ ================================================ FILE: monthandyearpicker/src/main/res/layout/month_picker_dialog.xml ================================================ ================================================ FILE: monthandyearpicker/src/main/res/layout/month_picker_view.xml ================================================ ================================================ FILE: monthandyearpicker/src/main/res/layout/month_view_header.xml ================================================ ================================================ FILE: monthandyearpicker/src/main/res/layout/year_label_text_view.xml ================================================ ================================================ FILE: monthandyearpicker/src/main/res/layout-land/month_picker_view.xml ================================================ ================================================ FILE: monthandyearpicker/src/main/res/layout-land/month_view_header.xml ================================================ ================================================ FILE: monthandyearpicker/src/main/res/layout-v11/month_picker_view.xml ================================================ ================================================ FILE: monthandyearpicker/src/main/res/layout-v11/year_label_text_view.xml ================================================ ================================================ FILE: monthandyearpicker/src/main/res/values/attrs.xml ================================================ ================================================ FILE: monthandyearpicker/src/main/res/values/colors.xml ================================================ #FFF #85FFFFFF #000000 #50000000 ================================================ FILE: monthandyearpicker/src/main/res/values/dimens.xml ================================================ 16dp 16dp 50dp 50dp ================================================ FILE: monthandyearpicker/src/main/res/values/strings.xml ================================================ MonthAndYear Picker MONTH YEAR ================================================ FILE: monthandyearpicker/src/main/res/values/styles.xml ================================================ ================================================ FILE: monthandyearpicker/src/main/res/values-w820dp/dimens.xml ================================================ 64dp ================================================ FILE: sample/.gitignore ================================================ /build ================================================ FILE: sample/build.gradle ================================================ apply plugin: 'com.android.application' android { compileSdkVersion 27 buildToolsVersion '27.0.3' defaultConfig { applicationId "com.whiteelephant.monthpickersample" minSdkVersion 14 targetSdkVersion 27 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation project(':monthandyearpicker') androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) implementation 'com.android.support:appcompat-v7:27.0.1' testImplementation 'junit:junit:4.12' } ================================================ FILE: sample/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /Users/prem/Library/Android/sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ================================================ FILE: sample/src/androidTest/java/com/whitelephant/monthpickersample/ExampleInstrumentedTest.java ================================================ package com.whitelephant.monthpickersample; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; /** * Instrumentation test, which will execute on an Android device. * * @see Testing documentation */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.whiteelephant.monthpickersample", appContext.getPackageName()); } } ================================================ FILE: sample/src/main/AndroidManifest.xml ================================================ ================================================ FILE: sample/src/main/java/com/whiteelephant/monthpickersample/MainActivity.java ================================================ package com.whiteelephant.monthpickersample; import android.app.DatePickerDialog; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.whiteelephant.monthpicker.MonthPickerDialog; import java.util.Calendar; import java.util.Locale; public class MainActivity extends AppCompatActivity { String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //applyLocale(); setNormalPicker(); // goto styles.xml and change the monthPickerStyles for below three layouts //setBottleView(); //chooseMonthOnly(); //chooseYearOnly(); } private void applyLocale() { Locale locale = new Locale("hi"); Locale.setDefault(locale); Resources res = getResources(); Configuration config = new Configuration(res.getConfiguration()); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); } private void setNormalPicker() { setContentView(R.layout.activity_main); final Calendar today = Calendar.getInstance(); findViewById(R.id.month_picker).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MonthPickerDialog.Builder builder = new MonthPickerDialog.Builder(MainActivity.this, new MonthPickerDialog.OnDateSetListener() { @Override public void onDateSet(int selectedMonth, int selectedYear) { Log.d(TAG, "selectedMonth : " + selectedMonth + " selectedYear : " + selectedYear); Toast.makeText(MainActivity.this, "Date set with month" + selectedMonth + " year " + selectedYear, Toast.LENGTH_SHORT).show(); } }, today.get(Calendar.YEAR), today.get(Calendar.MONTH)); builder.setActivatedMonth(Calendar.JULY) .setMinYear(1990) .setActivatedYear(2017) .setMaxYear(2030) .setMinMonth(Calendar.FEBRUARY) .setTitle("Select trading month") .setMonthRange(Calendar.FEBRUARY, Calendar.NOVEMBER) // .setMaxMonth(Calendar.OCTOBER) // .setYearRange(1890, 1890) // .setMonthAndYearRange(Calendar.FEBRUARY, Calendar.OCTOBER, 1890, 1890) //.showMonthOnly() // .showYearOnly() .setOnMonthChangedListener(new MonthPickerDialog.OnMonthChangedListener() { @Override public void onMonthChanged(int selectedMonth) { Log.d(TAG, "Selected month : " + selectedMonth); // Toast.makeText(MainActivity.this, " Selected month : " + selectedMonth, Toast.LENGTH_SHORT).show(); } }) .setOnYearChangedListener(new MonthPickerDialog.OnYearChangedListener() { @Override public void onYearChanged(int selectedYear) { Log.d(TAG, "Selected year : " + selectedYear); // Toast.makeText(MainActivity.this, " Selected year : " + selectedYear, Toast.LENGTH_SHORT).show(); } }) .build() .show(); } }); findViewById(R.id.date_picker).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar cal = Calendar.getInstance(); DatePickerDialog dialog = new DatePickerDialog(MainActivity.this, null, 2017, cal.get(Calendar.MONTH), cal.get(Calendar.DATE)); dialog.show(); } }); } private void chooseMonthOnly() { setContentView(R.layout.activity_choose_month); findViewById(R.id.choose_month).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MonthPickerDialog.Builder builder = new MonthPickerDialog.Builder(MainActivity.this, new MonthPickerDialog.OnDateSetListener() { @Override public void onDateSet(int selectedMonth, int selectedYear) { } }, /* activated number in year */ 3, 5); builder.showMonthOnly() .build() .show(); } }); } int choosenYear = 2017; private void chooseYearOnly() { setContentView(R.layout.activity_choose_year); final TextView year = (TextView) findViewById(R.id.year); findViewById(R.id.choose_year).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MonthPickerDialog.Builder builder = new MonthPickerDialog.Builder(MainActivity.this, new MonthPickerDialog.OnDateSetListener() { @Override public void onDateSet(int selectedMonth, int selectedYear) { year.setText(Integer.toString(selectedYear)); choosenYear = selectedYear; } }, choosenYear, 0); builder.showYearOnly() .setYearRange(1990, 2030) .build() .show(); } }); } private void setBottleView() { setContentView(R.layout.activity_bottle); LinearLayout chooseQty = (LinearLayout) findViewById(R.id.select_quantity); final TextView qty = (TextView) findViewById(R.id.qty); chooseQty.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MonthPickerDialog.Builder builder = new MonthPickerDialog.Builder(MainActivity.this, new MonthPickerDialog.OnDateSetListener() { @Override public void onDateSet(int selectedMonth, int selectedYear) { qty.setText(Integer.toString(selectedYear)); } }, /* activated number in year */ 3, 0); builder.setActivatedMonth(Calendar.JULY) // .setMaxMonth(Calendar.OCTOBER) //.setMinYear(1990) //.setActivatedYear(3) //.setMinMonth(Calendar.FEBRUARY) //.setMaxYear(2030) .setTitle("Select Quantity") //.setMonthRange(Calendar.FEBRUARY, Calendar.NOVEMBER) .setYearRange(1, 15) // .setMonthAndYearRange(Calendar.FEBRUARY, Calendar.OCTOBER, 1890, 1890) //.showMonthOnly() .showYearOnly() .build() .show(); } }); } } ================================================ FILE: sample/src/main/res/layout/activity_bottle.xml ================================================ ================================================ FILE: sample/src/main/res/layout/activity_choose_month.xml ================================================