├── sample
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-ldpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── values
│ │ │ ├── dimens.xml
│ │ │ ├── colors.xml
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ │ ├── values-w820dp
│ │ │ └── dimens.xml
│ │ └── layout
│ │ │ └── activity_sample.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── kunzisoft
│ │ └── switchdatetimesample
│ │ └── Sample.java
├── build.gradle
└── proguard-rules.pro
├── switchdatetime
├── .gitignore
├── src
│ └── main
│ │ ├── AndroidManifest.xml
│ │ ├── res
│ │ ├── drawable
│ │ │ └── ic_view_carousel_black_32dp.xml
│ │ ├── anim
│ │ │ ├── dialog_leave_to_left.xml
│ │ │ ├── dialog_enter_from_left.xml
│ │ │ ├── dialog_enter_from_right.xml
│ │ │ ├── dialog_enter_from_top.xml
│ │ │ ├── dialog_leave_to_bottom.xml
│ │ │ └── dialog_leave_to_right.xml
│ │ ├── values-xhdpi
│ │ │ └── dimens.xml
│ │ ├── values-sw340dp
│ │ │ └── dimens.xml
│ │ ├── values-sw260dp
│ │ │ └── dimens.xml
│ │ ├── values-sw600dp
│ │ │ └── dimens.xml
│ │ ├── values-sw720dp
│ │ │ └── dimens.xml
│ │ ├── layout
│ │ │ ├── year_text.xml
│ │ │ ├── year_text_indicator.xml
│ │ │ ├── time_header_label.xml
│ │ │ └── dialog_switch_datetime_picker.xml
│ │ ├── values-hdpi
│ │ │ └── dimens.xml
│ │ ├── values
│ │ │ ├── strings.xml
│ │ │ ├── attrs.xml
│ │ │ ├── dimens.xml
│ │ │ └── styles.xml
│ │ ├── values-ldpi
│ │ │ └── dimens.xml
│ │ ├── layout-ldrtl-v17
│ │ │ ├── time_header_label.xml
│ │ │ └── dialog_switch_datetime_picker.xml
│ │ ├── layout-ldrtl-land-v17
│ │ │ └── dialog_switch_datetime_picker.xml
│ │ └── layout-land
│ │ │ └── dialog_switch_datetime_picker.xml
│ │ └── java
│ │ └── com
│ │ └── kunzisoft
│ │ └── switchdatetime
│ │ ├── date
│ │ ├── OnYearSelectedListener.java
│ │ └── widget
│ │ │ ├── TextCircularIndicatorView.java
│ │ │ ├── YearPickerAdapter.java
│ │ │ └── ListPickerYearView.java
│ │ ├── time
│ │ └── widget
│ │ │ ├── AccessibleTextView.java
│ │ │ ├── TimeCircleView.java
│ │ │ ├── TimeAmPmCirclesView.java
│ │ │ ├── TimeRadialNumbersView.java
│ │ │ └── TimeRadialSelectorView.java
│ │ ├── Utils.java
│ │ └── SwitchDateTimeDialogFragment.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── art
├── logo.png
├── demo1.gif
├── demo2.gif
├── screen1.png
├── screen2.jpg
└── screen3.jpg
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── gradlew.bat
├── gradlew
├── ReadMe.md
└── LICENSE
/sample/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/switchdatetime/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':sample', ':switchdatetime'
2 |
--------------------------------------------------------------------------------
/art/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/art/logo.png
--------------------------------------------------------------------------------
/art/demo1.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/art/demo1.gif
--------------------------------------------------------------------------------
/art/demo2.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/art/demo2.gif
--------------------------------------------------------------------------------
/art/screen1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/art/screen1.png
--------------------------------------------------------------------------------
/art/screen2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/art/screen2.jpg
--------------------------------------------------------------------------------
/art/screen3.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/art/screen3.jpg
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/sample/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-ldpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/sample/src/main/res/mipmap-ldpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/sample/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/sample/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-ldpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/sample/src/main/res/mipmap-ldpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kunzisoft/Android-SwitchDateTimePicker/HEAD/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 | .directory
11 | .idea/
12 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | zipStoreBase=GRADLE_USER_HOME
4 | zipStorePath=wrapper/dists
5 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip
6 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #f44336
4 | #b71c1c
5 | #f44336
6 |
7 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Switch DateTime Picker
3 | Open DateTime Dialog
4 | Open DateTime Dialog with Neutral Button
5 | Clean
6 |
7 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/drawable/ic_view_carousel_black_32dp.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/anim/dialog_leave_to_left.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/anim/dialog_enter_from_left.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/anim/dialog_enter_from_right.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/anim/dialog_enter_from_top.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/anim/dialog_leave_to_bottom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/anim/dialog_leave_to_right.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/sample/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/java/com/kunzisoft/switchdatetime/date/OnYearSelectedListener.java:
--------------------------------------------------------------------------------
1 | package com.kunzisoft.switchdatetime.date;
2 |
3 | import android.view.View;
4 |
5 | /**
6 | * Listener for select year
7 | * @author JJamet
8 | */
9 | public interface OnYearSelectedListener {
10 | /**
11 | * Call when year is selected
12 | * @param view of event
13 | * @param year selected
14 | */
15 | void onYearSelected(View view, int year);
16 | }
17 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/values-xhdpi/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 300dp
5 |
6 | 264dp
7 | 302dp
8 |
9 | 192dp
10 | 220dp
11 |
12 | 28dp
13 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/values-sw340dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 160dp
5 |
6 | 280dp
7 |
8 | 280dp
9 | 280dp
10 |
11 | 260dp
12 | 220dp
13 |
14 | 16dp
15 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/values-sw260dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 142dp
5 |
6 |
7 | 190dp
8 |
9 | 200dp
10 | 230dp
11 |
12 | 180dp
13 | 160dp
14 |
15 | 14dp
16 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/values-sw600dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 200dp
5 |
6 |
7 | 380dp
8 |
9 | 410dp
10 | 468dp
11 |
12 | 272dp
13 | 310dp
14 |
15 | 28dp
16 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/values-sw720dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 200dp
5 |
6 |
7 | 420dp
8 |
9 |
10 | 416dp
11 | 476dp
12 |
13 | 272dp
14 | 310dp
15 |
16 | 48dp
17 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/layout/year_text.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
15 |
16 |
--------------------------------------------------------------------------------
/sample/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.application"
2 |
3 | android {
4 | compileSdkVersion 30
5 | buildToolsVersion "30.0.3"
6 |
7 | defaultConfig {
8 | applicationId "com.kunzisoft.switchdatetimepicker.sample"
9 | minSdkVersion 14
10 | targetSdkVersion 30
11 | versionCode 20
12 | versionName "2.1"
13 | }
14 |
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
19 | }
20 | }
21 | }
22 |
23 | dependencies {
24 | implementation 'androidx.appcompat:appcompat:1.3.1'
25 | implementation project(path: ":switchdatetime")
26 | }
27 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
10 |
11 |
12 |
17 |
18 |
--------------------------------------------------------------------------------
/sample/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /home/joker/Software/android-sdk-linux/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/switchdatetime/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /home/joker/Software/android-sdk-linux/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/layout/year_text_indicator.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
16 |
--------------------------------------------------------------------------------
/switchdatetime/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.library"
2 |
3 | android {
4 | compileSdkVersion 30
5 | buildToolsVersion "30.0.3"
6 |
7 | defaultConfig {
8 | minSdkVersion 14
9 | targetSdkVersion 30
10 | versionCode 20
11 | versionName "2.1"
12 | }
13 |
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | implementation 'androidx.appcompat:appcompat:1.3.1'
24 | implementation 'androidx.recyclerview:recyclerview:1.2.1'
25 | implementation 'com.github.prolificinteractive:material-calendarview:1.6.1'
26 | implementation 'com.google.android.material:material:1.4.0'
27 | }
28 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/values-hdpi/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 160dp
5 |
6 | 14sp
7 |
8 | 24sp
9 |
10 | 16sp
11 | 22sp
12 |
13 |
14 | 240dp
15 |
16 | 230dp
17 | 264dp
18 |
19 | 140dp
20 | 160dp
21 |
22 | 16dp
23 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | android.enableJetifier=true
13 | android.useAndroidX=true
14 | org.gradle.jvmargs=-Xmx1536m
15 |
16 | # When configured, Gradle will run in incubating parallel mode.
17 | # This option should only be used with decoupled projects. More details, visit
18 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
19 | # org.gradle.parallel=true
20 |
--------------------------------------------------------------------------------
/sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
13 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_sample.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
18 |
19 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | yyyy-MM-dd \'at\' HH:mm
4 |
5 |
6 | DateTime
7 |
8 |
9 | OK
10 | Cancel
11 |
12 |
13 | Image datetime
14 |
15 | Hours circular slider
16 | Select hours
17 | Minutes circular slider
18 | Select minutes
19 | --
20 | :
21 |
22 | sans-serif
23 | sans-serif
24 | %1$s deleted
25 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/java/com/kunzisoft/switchdatetime/time/widget/AccessibleTextView.java:
--------------------------------------------------------------------------------
1 | package com.kunzisoft.switchdatetime.time.widget;
2 |
3 | import android.content.Context;
4 | import android.os.Build;
5 | import androidx.appcompat.widget.AppCompatTextView;
6 | import android.util.AttributeSet;
7 | import android.view.accessibility.AccessibilityEvent;
8 | import android.view.accessibility.AccessibilityNodeInfo;
9 | import android.widget.Button;
10 |
11 | /**
12 | * Fake Button class, used so TextViews can announce themselves as Buttons, for accessibility.
13 | */
14 | public class AccessibleTextView extends AppCompatTextView {
15 |
16 | public AccessibleTextView(Context context, AttributeSet attrs) {
17 | super(context, attrs);
18 | }
19 |
20 | @Override
21 | public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
22 | if (Build.VERSION.SDK_INT >= 14) {
23 | super.onInitializeAccessibilityEvent(event);
24 | event.setClassName(Button.class.getName());
25 | }
26 | }
27 |
28 | @Override
29 | public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
30 | if (Build.VERSION.SDK_INT >= 14) {
31 | super.onInitializeAccessibilityNodeInfo(info);
32 | info.setClassName(Button.class.getName());
33 | }
34 | }
35 | }
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/values-ldpi/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 146dp
5 |
6 | 14sp
7 |
8 | 14sp
9 | 14sp
10 | 14sp
11 |
12 |
13 | 160dp
14 |
15 |
16 |
17 |
18 | 168dp
19 | 194dp
20 |
26 |
27 | 140dp
28 | 162dp
29 |
35 |
36 | 16dp
37 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/values/attrs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/java/com/kunzisoft/switchdatetime/Utils.java:
--------------------------------------------------------------------------------
1 | package com.kunzisoft.switchdatetime;
2 |
3 | import android.animation.Keyframe;
4 | import android.animation.ObjectAnimator;
5 | import android.animation.PropertyValuesHolder;
6 | import android.annotation.SuppressLint;
7 | import android.os.Build;
8 | import android.view.View;
9 | import android.view.accessibility.AccessibilityManager;
10 |
11 | public class Utils {
12 |
13 | private static final int ANIMATION_DELAY = 0;
14 | private static final int PULSE_ANIMATOR_DURATION = 544;
15 |
16 | public static void animLabelElement(View view) {
17 | ObjectAnimator monthDayAnim = getPulseAnimator(view, 0.9F, 1.05F);
18 | monthDayAnim.setStartDelay(ANIMATION_DELAY);
19 | monthDayAnim.start();
20 | }
21 |
22 | public static ObjectAnimator getPulseAnimator(View labelToAnimate, float decreaseRatio, float increaseRatio) {
23 | Keyframe k0 = Keyframe.ofFloat(0f, 1f);
24 | Keyframe k1 = Keyframe.ofFloat(0.275f, decreaseRatio);
25 | Keyframe k2 = Keyframe.ofFloat(0.69f, increaseRatio);
26 | Keyframe k3 = Keyframe.ofFloat(1f, 1f);
27 |
28 | PropertyValuesHolder scaleX = PropertyValuesHolder.ofKeyframe("scaleX", k0, k1, k2, k3);
29 | PropertyValuesHolder scaleY = PropertyValuesHolder.ofKeyframe("scaleY", k0, k1, k2, k3);
30 | ObjectAnimator pulseAnimator = ObjectAnimator.ofPropertyValuesHolder(labelToAnimate, scaleX, scaleY);
31 | pulseAnimator.setDuration(PULSE_ANIMATOR_DURATION);
32 |
33 | return pulseAnimator;
34 | }
35 |
36 | public static boolean isTouchExplorationEnabled(AccessibilityManager accessibilityManager) {
37 | return Build.VERSION.SDK_INT >= 14 && accessibilityManager.isTouchExplorationEnabled();
38 | }
39 |
40 | /**
41 | * Try to speak the specified text, for accessibility. Only available on JB or later.
42 | * @param text Text to announce.
43 | */
44 | @SuppressLint("NewApi")
45 | public static void tryAccessibilityAnnounce(View view, CharSequence text) {
46 | if (Build.VERSION.SDK_INT >= 16 && view != null && text != null) {
47 | view.announceForAccessibility(text);
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 200dp
5 |
6 | 18sp
7 |
8 | 24sp
9 | 12sp
10 | 32dip
11 | 180dp
12 | 54dp
13 | 16sp
14 | 6dip
15 | -30dp
16 | 4dip
17 | 14dip
18 |
19 | 16sp
20 | 26sp
21 |
22 | 64dip
23 |
24 |
25 | 320dp
26 |
27 |
28 |
29 | 340dp
30 | 390dp
31 |
32 | 190dp
33 | 220dp
34 |
35 | 24dp
36 |
37 | 270dip
38 |
39 | - 0.82
40 | - 0.85
41 |
42 | - 0.81
43 | - 0.60
44 | - 0.83
45 |
46 | - 0.17
47 | - 0.14
48 | - 0.11
49 |
50 | - 0.19
51 | - 0.16
52 |
53 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/java/com/kunzisoft/switchdatetime/date/widget/TextCircularIndicatorView.java:
--------------------------------------------------------------------------------
1 | package com.kunzisoft.switchdatetime.date.widget;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.content.Context;
5 | import android.content.res.TypedArray;
6 | import android.graphics.Canvas;
7 | import android.graphics.Color;
8 | import android.graphics.Paint;
9 | import androidx.annotation.ColorInt;
10 | import androidx.appcompat.widget.AppCompatTextView;
11 | import android.util.AttributeSet;
12 |
13 | import com.kunzisoft.switchdatetime.R;
14 |
15 | /**
16 | * TextView with circular colored background
17 | * @author JJamet
18 | */
19 | public class TextCircularIndicatorView extends AppCompatTextView {
20 |
21 | private int mCircleColor = Color.BLUE;
22 | private Paint mCirclePaint = new Paint();
23 |
24 | public TextCircularIndicatorView(Context context) {
25 | this(context, null, 0);
26 | }
27 |
28 | public TextCircularIndicatorView(Context context, AttributeSet attrs) {
29 | this(context, attrs, 0);
30 | }
31 |
32 | public TextCircularIndicatorView(Context context, AttributeSet attrs, int defStyleAttr) {
33 | super(context, attrs, defStyleAttr);
34 | init(attrs);
35 | }
36 |
37 | /**
38 | * Initialize constructor
39 | */
40 | private void init(AttributeSet attrs) {
41 |
42 | if(attrs != null) {
43 | TypedArray circularIndicatorTypedArray = getContext().obtainStyledAttributes(attrs, R.styleable.TextCircularIndicatorView);
44 | setCircleColor(circularIndicatorTypedArray.getColor(R.styleable.TextCircularIndicatorView_colorCircleIndicator, mCircleColor));
45 | circularIndicatorTypedArray.recycle();
46 | }
47 |
48 | mCirclePaint.setFakeBoldText(true);
49 | mCirclePaint.setAntiAlias(true);
50 | mCirclePaint.setColor(mCircleColor);
51 | mCirclePaint.setTextAlign(Paint.Align.CENTER);
52 | mCirclePaint.setStyle(Paint.Style.FILL);
53 | }
54 |
55 | @SuppressLint("GetContentDescriptionOverride")
56 | @Override
57 | public CharSequence getContentDescription() {
58 | return getText();
59 | }
60 |
61 | @Override
62 | public void onDraw(Canvas canvas) {
63 | int width = getWidth();
64 | int height = getHeight();
65 | int radius = Math.min(width, height) / 2;
66 | canvas.drawCircle(width / 2, height / 2, radius, mCirclePaint);
67 | super.onDraw(canvas);
68 | }
69 |
70 | /**
71 | * Get color of background circle
72 | */
73 | public int getCircleColor() {
74 | return mCircleColor;
75 | }
76 |
77 | /**
78 | * Set color of background circle
79 | */
80 | public void setCircleColor(@ColorInt int color) {
81 | this.mCircleColor = color;
82 | }
83 |
84 | }
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/layout-ldrtl-v17/time_header_label.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
21 |
22 |
32 |
33 |
42 |
43 |
51 |
52 |
59 |
69 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
11 |
14 |
15 |
16 |
19 |
20 |
21 |
26 |
27 |
28 |
32 |
33 |
34 |
43 |
44 |
45 |
49 |
50 |
55 |
56 |
57 |
60 |
61 |
62 |
66 |
67 |
68 |
72 |
73 |
74 |
79 |
80 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/layout/time_header_label.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
20 |
21 |
32 |
33 |
44 |
45 |
54 |
55 |
64 |
75 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/kunzisoft/switchdatetimesample/Sample.java:
--------------------------------------------------------------------------------
1 | package com.kunzisoft.switchdatetimesample;
2 |
3 | import android.os.Bundle;
4 |
5 | import androidx.appcompat.app.AppCompatActivity;
6 |
7 | import android.util.Log;
8 | import android.view.View;
9 | import android.widget.Button;
10 | import android.widget.TextView;
11 |
12 | import com.kunzisoft.switchdatetime.SwitchDateTimeDialogFragment;
13 |
14 | import java.text.SimpleDateFormat;
15 | import java.util.Calendar;
16 | import java.util.Date;
17 | import java.util.GregorianCalendar;
18 | import java.util.Locale;
19 | import java.util.TimeZone;
20 |
21 | /**
22 | * Sample class for an example of using the API SwitchDateTimePicker
23 | *
24 | * @author JJamet
25 | */
26 | public class Sample extends AppCompatActivity {
27 |
28 | private static final String TAG = "Sample";
29 |
30 | private static final String TAG_DATETIME_FRAGMENT = "TAG_DATETIME_FRAGMENT";
31 |
32 | private static final String STATE_TEXTVIEW = "STATE_TEXTVIEW";
33 | private TextView textView;
34 |
35 | private SwitchDateTimeDialogFragment dateTimeFragment;
36 |
37 | @Override
38 | protected void onCreate(Bundle savedInstanceState) {
39 | super.onCreate(savedInstanceState);
40 | setContentView(R.layout.activity_sample);
41 |
42 | textView = findViewById(R.id.textView);
43 | if (savedInstanceState != null) {
44 | // Restore value from saved state
45 | textView.setText(savedInstanceState.getCharSequence(STATE_TEXTVIEW));
46 | }
47 |
48 | // Construct SwitchDateTimePicker
49 | dateTimeFragment = (SwitchDateTimeDialogFragment) getSupportFragmentManager().findFragmentByTag(TAG_DATETIME_FRAGMENT);
50 | if (dateTimeFragment == null) {
51 | dateTimeFragment = SwitchDateTimeDialogFragment.newInstance(
52 | getString(R.string.label_datetime_dialog),
53 | getString(android.R.string.ok),
54 | getString(android.R.string.cancel),
55 | getString(R.string.clean),// Optional
56 | "en"
57 | );
58 | }
59 |
60 | // Optionally define a timezone
61 | dateTimeFragment.setTimeZone(TimeZone.getDefault());
62 |
63 | // Init format
64 | final SimpleDateFormat myDateFormat = new SimpleDateFormat("d MMM yyyy HH:mm", java.util.Locale.getDefault());
65 | // Assign unmodifiable values
66 | dateTimeFragment.set24HoursMode(false);
67 | dateTimeFragment.setHighlightAMPMSelection(false);
68 | dateTimeFragment.setMinimumDateTime(new GregorianCalendar(2015, Calendar.JANUARY, 1).getTime());
69 | dateTimeFragment.setMaximumDateTime(new GregorianCalendar(2025, Calendar.DECEMBER, 31).getTime());
70 |
71 | // Define new day and month format
72 | try {
73 | dateTimeFragment.setSimpleDateMonthAndDayFormat(new SimpleDateFormat("MMMM dd", Locale.getDefault()));
74 | } catch (SwitchDateTimeDialogFragment.SimpleDateMonthAndDayFormatException e) {
75 | Log.e(TAG, e.getMessage());
76 | }
77 |
78 | // Set listener for date
79 | // Or use dateTimeFragment.setOnButtonClickListener(new SwitchDateTimeDialogFragment.OnButtonClickListener() {
80 | dateTimeFragment.setOnButtonClickListener(new SwitchDateTimeDialogFragment.OnButtonWithNeutralClickListener() {
81 | @Override
82 | public void onPositiveButtonClick(Date date) {
83 | textView.setText(myDateFormat.format(date));
84 | }
85 |
86 | @Override
87 | public void onNegativeButtonClick(Date date) {
88 | // Do nothing
89 | }
90 |
91 | @Override
92 | public void onNeutralButtonClick(Date date) {
93 | // Optional if neutral button does'nt exists
94 | textView.setText("");
95 | }
96 | });
97 |
98 | Button buttonView = findViewById(R.id.button);
99 | buttonView.setOnClickListener(new View.OnClickListener() {
100 | @Override
101 | public void onClick(View view) {
102 | // Re-init each time
103 | dateTimeFragment.startAtCalendarView();
104 | dateTimeFragment.setDefaultDateTime(new GregorianCalendar(2017, Calendar.MARCH, 4, 15, 20).getTime());
105 | dateTimeFragment.show(getSupportFragmentManager(), TAG_DATETIME_FRAGMENT);
106 | }
107 | });
108 | }
109 |
110 | @Override
111 | public void onSaveInstanceState(Bundle savedInstanceState) {
112 | // Save the current textView
113 | savedInstanceState.putCharSequence(STATE_TEXTVIEW, textView.getText());
114 | super.onSaveInstanceState(savedInstanceState);
115 | }
116 | }
--------------------------------------------------------------------------------
/switchdatetime/src/main/java/com/kunzisoft/switchdatetime/time/widget/TimeCircleView.java:
--------------------------------------------------------------------------------
1 | package com.kunzisoft.switchdatetime.time.widget;
2 | /*
3 | * Copyright (C) 2013 The Android Open Source Project
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | import android.content.Context;
19 | import android.content.res.Resources;
20 | import android.content.res.TypedArray;
21 | import android.graphics.Canvas;
22 | import android.graphics.Color;
23 | import android.graphics.Paint;
24 | import android.util.AttributeSet;
25 | import android.util.Log;
26 | import android.view.View;
27 |
28 | import com.kunzisoft.switchdatetime.R;
29 |
30 | /**
31 | * Draws a simple white circle on which the numbers will be drawn.
32 | */
33 | public class TimeCircleView extends View {
34 | private static final String TAG = "CircleView";
35 |
36 | private final Paint mPaint = new Paint();
37 | private boolean mIs24HourMode;
38 | private int mCircleBackgroundColor;
39 | private int mCenterCircleColor;
40 | private float mCircleRadiusMultiplier;
41 | private float mAmPmCircleRadiusMultiplier;
42 | private boolean mIsInitialized;
43 |
44 | private boolean mDrawValuesReady;
45 | private int mXCenter;
46 | private int mYCenter;
47 | private int mCircleRadius;
48 |
49 |
50 | public TimeCircleView(Context context) {
51 | this(context, null, 0);
52 | }
53 |
54 | public TimeCircleView(Context context, AttributeSet attrs) {
55 | this(context, attrs, 0);
56 | }
57 |
58 | public TimeCircleView(Context context, AttributeSet attrs, int defStyleAttr) {
59 | super(context, attrs, defStyleAttr);
60 |
61 | TypedArray switchTimeColorTypedArray = getContext().obtainStyledAttributes(attrs, R.styleable.TimeCircleView);
62 | setCircleColor(switchTimeColorTypedArray.getColor(R.styleable.TimeCircleView_timeCircleColor, Color.WHITE));
63 | setCenterColor(switchTimeColorTypedArray.getColor(R.styleable.TimeCircleView_timeCenterColor, Color.BLACK));
64 | switchTimeColorTypedArray.recycle();
65 |
66 | mPaint.setAntiAlias(true);
67 |
68 | mIsInitialized = false;
69 | }
70 |
71 | public void initialize(Context context, boolean is24HourMode) {
72 | if (mIsInitialized) {
73 | Log.e(TAG, "CircleView may only be initialized once.");
74 | return;
75 | }
76 |
77 | Resources res = context.getResources();
78 | mIs24HourMode = is24HourMode;
79 | if (is24HourMode) {
80 | mCircleRadiusMultiplier = Float.parseFloat(
81 | res.getString(R.string.circle_radius_multiplier_24HourMode));
82 | } else {
83 | mCircleRadiusMultiplier = Float.parseFloat(
84 | res.getString(R.string.circle_radius_multiplier));
85 | mAmPmCircleRadiusMultiplier =
86 | Float.parseFloat(res.getString(R.string.ampm_circle_radius_multiplier));
87 | }
88 |
89 | mIsInitialized = true;
90 | }
91 |
92 |
93 | @Override
94 | public void onDraw(Canvas canvas) {
95 | int viewWidth = getWidth();
96 | if (viewWidth == 0 || !mIsInitialized) {
97 | return;
98 | }
99 |
100 | if (!mDrawValuesReady) {
101 | mXCenter = getWidth() / 2;
102 | mYCenter = getHeight() / 2;
103 | mCircleRadius = (int) (Math.min(mXCenter, mYCenter) * mCircleRadiusMultiplier);
104 |
105 | if (!mIs24HourMode) {
106 | // We'll need to draw the AM/PM circles, so the main circle will need to have
107 | // a slightly higher center. To keep the entire view centered vertically, we'll
108 | // have to push it up by half the radius of the AM/PM circles.
109 | int amPmCircleRadius = (int) (mCircleRadius * mAmPmCircleRadiusMultiplier);
110 | mYCenter -= amPmCircleRadius / 2;
111 | }
112 |
113 | mDrawValuesReady = true;
114 | }
115 |
116 | // Draw the white circle.
117 | mPaint.setColor(mCircleBackgroundColor);
118 | canvas.drawCircle(mXCenter, mYCenter, mCircleRadius, mPaint);
119 |
120 | // Draw a small black circle in the center.
121 | mPaint.setColor(mCenterCircleColor);
122 | canvas.drawCircle(mXCenter, mYCenter, 2, mPaint);
123 | }
124 |
125 | public int getCircleColor() {
126 | return mCircleBackgroundColor;
127 | }
128 |
129 | public void setCircleColor(int circleBackgroundColor) {
130 | this.mCircleBackgroundColor = circleBackgroundColor;
131 | }
132 |
133 | public int getCenterColor() {
134 | return mCenterCircleColor;
135 | }
136 |
137 | public void setCenterColor(int centerColor) {
138 | this.mCenterCircleColor = centerColor;
139 | }
140 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/layout-ldrtl-v17/dialog_switch_datetime_picker.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
15 |
16 |
24 |
25 |
34 |
35 |
46 |
47 |
48 |
55 |
56 |
63 |
64 |
74 |
75 |
85 |
86 |
87 |
88 |
89 |
97 |
105 |
113 |
114 |
115 |
119 |
127 |
128 |
129 |
130 |
139 |
140 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/java/com/kunzisoft/switchdatetime/date/widget/YearPickerAdapter.java:
--------------------------------------------------------------------------------
1 | package com.kunzisoft.switchdatetime.date.widget;
2 |
3 | import androidx.recyclerview.widget.RecyclerView;
4 | import android.view.LayoutInflater;
5 | import android.view.View;
6 | import android.view.ViewGroup;
7 | import android.widget.TextView;
8 |
9 | import com.kunzisoft.switchdatetime.R;
10 |
11 | import java.text.SimpleDateFormat;
12 | import java.util.ArrayList;
13 | import java.util.Calendar;
14 | import java.util.List;
15 | import java.util.Locale;
16 |
17 | /**
18 | * Adapter for manage elements of ListPickerYearView
19 | * @author JJamet
20 | */
21 | class YearPickerAdapter extends RecyclerView.Adapter {
22 |
23 | private static final int LIST_ITEM_TYPE_STANDARD = 0;
24 | private static final int LIST_ITEM_TYPE_INDICATOR = 1;
25 |
26 | public static final int UNDEFINED = -1;
27 |
28 | private SimpleDateFormat yearFormat;
29 | private Calendar calendar;
30 |
31 | private List listYears;
32 | private Integer selectedYear;
33 | private int positionSelectedYear;
34 |
35 | private OnClickYearListener onClickYearListener;
36 |
37 | /**
38 | * Initialize adapter with list of years and element selected
39 | */
40 | YearPickerAdapter() {
41 | this.listYears = new ArrayList<>();
42 | this.selectedYear = UNDEFINED;
43 | this.yearFormat = new SimpleDateFormat("yyyy", Locale.getDefault());
44 | this.calendar = Calendar.getInstance();
45 | }
46 |
47 | @Override
48 | public long getItemId(int i) {
49 | return listYears.get(i);
50 | }
51 |
52 | @Override
53 | public int getItemCount() {
54 | return listYears.size();
55 | }
56 |
57 | @Override
58 | public TextIndicatorViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
59 | switch (viewType) {
60 | default:
61 | case LIST_ITEM_TYPE_STANDARD:
62 | return new TextIndicatorViewHolder(
63 | LayoutInflater.from(parent.getContext()).inflate(R.layout.year_text, parent, false));
64 | case LIST_ITEM_TYPE_INDICATOR:
65 | return new TextIndicatorViewHolder(
66 | LayoutInflater.from(parent.getContext()).inflate(R.layout.year_text_indicator, parent, false));
67 | }
68 | }
69 |
70 | @Override
71 | public void onBindViewHolder(TextIndicatorViewHolder holder, int position) {
72 | Integer currentYear = listYears.get(position);
73 |
74 | calendar.set(Calendar.YEAR, currentYear);
75 | holder.textView.setText(yearFormat.format(calendar.getTime()));
76 |
77 | if(onClickYearListener != null)
78 | holder.container.setOnClickListener(new BufferYearClickListener(currentYear, position));
79 | }
80 |
81 | @Override
82 | public int getItemViewType(int position) {
83 | if(listYears.get(position).equals(selectedYear))
84 | return LIST_ITEM_TYPE_INDICATOR;
85 | else
86 | return LIST_ITEM_TYPE_STANDARD;
87 | }
88 |
89 | /**
90 | * Get the list of years
91 | * @return years
92 | */
93 | public List getListYears() {
94 | return listYears;
95 | }
96 |
97 | /**
98 | * Assign the list of years, replace current list
99 | * @param listYears list of years
100 | */
101 | public void setListYears(List listYears) {
102 | this.listYears = listYears;
103 | }
104 |
105 | /**
106 | * Get the current selected year or value of UNDEFINED if undefined
107 | */
108 | public int getSelectedYear() {
109 | return selectedYear;
110 | }
111 |
112 | /**
113 | * Assign the current selected year
114 | * @param selectedYear year selected
115 | */
116 | public void setSelectedYear(int selectedYear) throws SelectYearException {
117 | if(!listYears.contains(selectedYear))
118 | throw new SelectYearException(selectedYear, listYears);
119 | this.selectedYear = selectedYear;
120 | this.positionSelectedYear = listYears.indexOf(selectedYear);
121 | }
122 |
123 | /**
124 | * Get position of selected year or value of UNDEFINED if undefined
125 | */
126 | public int getPositionSelectedYear() {
127 | return positionSelectedYear;
128 | }
129 |
130 | /**
131 | * Get the listener called when the year is clicked
132 | */
133 | public OnClickYearListener getOnClickYearListener() {
134 | return onClickYearListener;
135 | }
136 |
137 | /**
138 | * Set the listener called when the year is clicked
139 | * @param onClickYearListener year listener
140 | */
141 | public void setOnClickYearListener(OnClickYearListener onClickYearListener) {
142 | this.onClickYearListener = onClickYearListener;
143 | }
144 |
145 | /**
146 | * Listener when a click on Year item is performed
147 | */
148 | public interface OnClickYearListener {
149 | /**
150 | * Called on click
151 | * @param view Current view clicked
152 | * @param year Year of current item clicked
153 | * @param position Position of item clicked
154 | */
155 | void onItemYearClick(View view, Integer year, int position);
156 | }
157 |
158 | private class BufferYearClickListener implements View.OnClickListener {
159 |
160 | private Integer year;
161 | private int position;
162 |
163 | BufferYearClickListener(Integer yearClicked, int position) {
164 | this.year = yearClicked;
165 | this.position = position;
166 | }
167 |
168 | @Override
169 | public void onClick(View view) {
170 | onClickYearListener.onItemYearClick(view, year, position);
171 | }
172 | }
173 |
174 | /**
175 | * Holder for TextIndicatorView
176 | */
177 | class TextIndicatorViewHolder extends RecyclerView.ViewHolder {
178 | /**
179 | * Views of year
180 | */
181 | private ViewGroup container;
182 | private TextView textView;
183 |
184 | TextIndicatorViewHolder(View itemView) {
185 | super(itemView);
186 | container = itemView.findViewById(R.id.year_element_container);
187 | textView = itemView.findViewById(R.id.year_textView);
188 | }
189 | }
190 |
191 | /**
192 | * Exception class for year selected
193 | */
194 | class SelectYearException extends Exception {
195 | SelectYearException(Integer yearSelected, List listYears) {
196 | super("Year selected " + yearSelected + " must be in list of years : " + listYears);
197 | }
198 | }
199 | }
200 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/java/com/kunzisoft/switchdatetime/date/widget/ListPickerYearView.java:
--------------------------------------------------------------------------------
1 | package com.kunzisoft.switchdatetime.date.widget;
2 |
3 | import android.content.Context;
4 | import android.content.res.Resources;
5 | import android.content.res.TypedArray;
6 | import androidx.recyclerview.widget.LinearLayoutManager;
7 | import androidx.recyclerview.widget.RecyclerView;
8 | import android.util.AttributeSet;
9 | import android.util.Log;
10 | import android.view.View;
11 | import android.view.ViewGroup;
12 |
13 | import com.kunzisoft.switchdatetime.R;
14 | import com.kunzisoft.switchdatetime.date.OnYearSelectedListener;
15 |
16 | import java.util.ArrayList;
17 |
18 | /**
19 | * ListView for select one year, year selected is highlight
20 | * To get the year, assign an OnYearSelectedListener
21 | * @see com.kunzisoft.switchdatetime.date.OnYearSelectedListener#onYearSelected(View, int)
22 | * @author JJamet
23 | */
24 | public class ListPickerYearView extends RecyclerView implements YearPickerAdapter.OnClickYearListener{
25 |
26 | private final static String TAG = "ListPickerYearView";
27 |
28 | private int minYear = 1970;
29 | private int maxYear = 2100;
30 | private int currentYear;
31 |
32 | private YearPickerAdapter mAdapter;
33 | private OnYearSelectedListener yearChangeListener;
34 | private int mChildSize;
35 | private int mViewSize;
36 |
37 | public ListPickerYearView(Context context) {
38 | this(context, null, 0);
39 | }
40 |
41 | public ListPickerYearView(Context context, AttributeSet attrs) {
42 | this(context, attrs, 0);
43 | }
44 |
45 | public ListPickerYearView(Context context, AttributeSet attrs, int defStyleAttr) {
46 | super(context, attrs, defStyleAttr);
47 | init(context, attrs);
48 | }
49 |
50 | private void init(Context context, AttributeSet attrs) {
51 | setLayoutManager(new LinearLayoutManager(context));
52 |
53 | if(attrs != null) {
54 | TypedArray yearTypedArray = getContext().obtainStyledAttributes(attrs, R.styleable.ListPickerYearView);
55 | setMinYear(yearTypedArray.getInt(R.styleable.ListPickerYearView_minYear, minYear));
56 | setMaxYear(yearTypedArray.getInt(R.styleable.ListPickerYearView_maxYear, minYear));
57 | currentYear = yearTypedArray.getInt(R.styleable.ListPickerYearView_defaultYear, YearPickerAdapter.UNDEFINED);
58 | yearTypedArray.recycle();
59 | }
60 |
61 | setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
62 |
63 | Resources resources = context.getResources();
64 | mViewSize = resources.getDimensionPixelOffset(R.dimen.date_picker_view_animator_height);
65 | mChildSize = resources.getDimensionPixelOffset(R.dimen.year_label_height);
66 |
67 | setVerticalFadingEdgeEnabled(true);
68 | setFadingEdgeLength(mChildSize / 3);
69 |
70 | mAdapter = new YearPickerAdapter();
71 | setAdapter(mAdapter);
72 |
73 | mAdapter.setOnClickYearListener(this);
74 |
75 | refreshAndCenter();
76 | }
77 |
78 | /**
79 | * Assign years to adapter only if view is init
80 | */
81 | private void injectYearsInAdapter() {
82 | if(mAdapter != null) {
83 | ArrayList years = new ArrayList<>();
84 | for (int year = minYear; year <= maxYear; year++) {
85 | years.add(year);
86 | }
87 | mAdapter.setListYears(years);
88 | mAdapter.notifyDataSetChanged();
89 | }
90 | }
91 |
92 | /**
93 | * Refresh list and center on the selected year
94 | */
95 | public void refreshAndCenter() {
96 | mAdapter.notifyDataSetChanged();
97 | centerListOn(currentYear - minYear -1);
98 | }
99 |
100 | @Override
101 | public void onItemYearClick(View view, Integer year, int position) {
102 | int positionOldYear = mAdapter.getPositionSelectedYear();
103 | currentYear = year;
104 |
105 | // TODO Vibrate
106 | //mController.tryVibrate();
107 | if(yearChangeListener != null) {
108 | yearChangeListener.onYearSelected(view, year);
109 | }
110 |
111 | try {
112 | mAdapter.setSelectedYear(currentYear);
113 | } catch (YearPickerAdapter.SelectYearException e) {
114 | Log.e(TAG, e.getMessage());
115 | }
116 | mAdapter.notifyDataSetChanged();
117 | mAdapter.notifyItemChanged(positionOldYear);
118 | mAdapter.notifyItemChanged(position);
119 | }
120 |
121 | /**
122 | * Center list on the selected year
123 | * @param position of year in the list
124 | */
125 | public void centerListOn(final int position) {
126 | getLayoutManager().scrollToPosition(position);
127 | try {
128 | getLayoutManager().scrollVerticallyBy(mViewSize / 2 - mChildSize / 2, null, null);
129 | } catch(Exception e){
130 | Log.w(TAG, "Can't scroll more");
131 | }
132 | }
133 |
134 | /**
135 | * Attach listener for select year
136 | * @param onYearSelectedListener listener
137 | */
138 | public void setDatePickerListener(OnYearSelectedListener onYearSelectedListener) {
139 | this.yearChangeListener = onYearSelectedListener;
140 | }
141 |
142 | /**
143 | * Get current minYear
144 | * @return
145 | */
146 | public int getMinYear() {
147 | return minYear;
148 | }
149 |
150 | /**
151 | * Set minimum year of list
152 | * @param minYear minimum year
153 | */
154 | public void setMinYear(int minYear) {
155 | this.minYear = minYear;
156 | injectYearsInAdapter();
157 | }
158 |
159 | /**
160 | * Get maximum year of list
161 | * @return
162 | */
163 | public int getMaxYear() {
164 | return maxYear;
165 | }
166 |
167 | /**
168 | * Set maximum year of list
169 | * @param maxYear
170 | */
171 | public void setMaxYear(int maxYear) {
172 | this.maxYear = maxYear;
173 | injectYearsInAdapter();
174 | }
175 |
176 | /**
177 | * Get current year selected
178 | * @return
179 | */
180 | public int getYearSelected() {
181 | return currentYear;
182 | }
183 |
184 | /**
185 | * Assign current year and refresh list
186 | * @param year
187 | */
188 | public void assignCurrentYear(int year) {
189 | currentYear = year;
190 | if(mAdapter != null) {
191 | try {
192 | mAdapter.setSelectedYear(currentYear);
193 | } catch (YearPickerAdapter.SelectYearException e) {
194 | Log.e(TAG, e.getMessage());
195 | }
196 | }
197 | refreshAndCenter();
198 | }
199 | }
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/layout/dialog_switch_datetime_picker.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
14 |
15 |
23 |
24 |
34 |
35 |
48 |
49 |
50 |
58 |
59 |
66 |
67 |
78 |
79 |
91 |
92 |
93 |
94 |
95 |
103 |
111 |
119 |
120 |
121 |
125 |
133 |
134 |
135 |
136 |
145 |
146 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/layout-ldrtl-land-v17/dialog_switch_datetime_picker.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
14 |
15 |
23 |
24 |
32 |
33 |
44 |
45 |
46 |
53 |
54 |
62 |
63 |
73 |
74 |
84 |
85 |
86 |
87 |
98 |
105 |
109 |
118 |
119 |
120 |
121 |
125 |
133 |
134 |
135 |
144 |
145 |
146 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/res/layout-land/dialog_switch_datetime_picker.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
14 |
15 |
23 |
24 |
33 |
34 |
47 |
48 |
49 |
57 |
58 |
67 |
68 |
79 |
80 |
92 |
93 |
94 |
95 |
108 |
115 |
119 |
129 |
130 |
131 |
132 |
136 |
144 |
145 |
146 |
155 |
156 |
157 |
--------------------------------------------------------------------------------
/ReadMe.md:
--------------------------------------------------------------------------------
1 | [](http://android-arsenal.com/details/1/4513)
2 |
3 | # Android SwitchDateTime Picker
4 |
5 |
SwitchDateTime Picker is a library for select a *Date* object in dialog with a DatePicker (Calendar) and a TimePicker (Clock) in the same UI.
6 |
7 |
8 |
9 |
10 | ## Contributions
11 |
12 | You can contribute in different ways to help us on our work.
13 |
14 | * Add features by a pull request.
15 | * Help to translate into your language
16 | * [Donate](https://www.kunzisoft.com/donation) 人◕ ‿‿ ◕人Y for a better service and a quick development of your features.
17 |
18 | ## Installation
19 | Add the JitPack repository in your build.gradle at the end of repositories:
20 | ```
21 | allprojects {
22 | repositories {
23 | ...
24 | maven { url "https://jitpack.io" }
25 | }
26 | }
27 | ```
28 | And add the dependency
29 | [](https://jitpack.io/#Kunzisoft/Android-SwitchDateTimePicker)
30 | *replacing ${version} with the version number in jitpack*
31 |
32 | ```
33 | dependencies {
34 | compile 'com.github.Kunzisoft:Android-SwitchDateTimePicker:${version}'
35 | }
36 | ```
37 |
38 | ## Usage
39 |
40 | ### SimpleDateFormat for Day and Month
41 | You can specify a particular [*SimpleDateFormat*](https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html) for value of Day and Month with **setSimpleDateMonthAndDayFormat(SimpleDateFormat format)**
42 | Warning, the format must satisfy the regular expression : **(M|w|W|D|d|F|E|u|\s)***
43 | , for example *dd MMMM*
44 |
45 | ### 24 Hours mode
46 | By default, time is in 12 hours mode, If you want a 24-hour display, use:
47 | `dateTimeFragment.set24HoursMode(true);`
48 | before the "show"
49 |
50 | #### Hightligh selected AM / PM
51 | In 24 hours mode, If you want to highlight the selected AM or PM, use :
52 | `dateTimeFragment.setHighlightAMPMSelection(true);`
53 |
54 | ### Start with a specific view
55 | For launch Dialog with a specific view, call :
56 | `dateTimeFragment.startAtTimeView();`, `dateTimeFragment.startAtCalendarView();` or `dateTimeFragment.startAtYearView();`
57 | before the "show"
58 |
59 | ### Define minimum and maximum
60 | For just allow selection after or/and before dates, use :
61 | `dateTimeFragment.setMinimumDateTime(Date minimum);`
62 | and
63 | `dateTimeFragment.setMaximumDateTime(Date maximum);`
64 |
65 | ### TimeZone
66 | Optionally define a timezone :
67 | `dateTimeFragment.setTimeZone(TimeZone.getDefault());`
68 |
69 | ### Style
70 | You can customize the style to change color, bold, etc... of each element.
71 | You need to use a Theme.AppCompat theme (or descendant) with SwitchDateTime's activity. (`compile 'com.android.support:appcompat-v7:25.1.0'` in gradle)
72 |
73 |
74 |
75 | In your *styles.xml*, you can redefine each style separately, but you must keep each item, for example : change size of "year label"
76 | ```
77 |
78 |
79 |
85 |
86 |
87 |
88 |
93 |
94 |
95 | ```
96 | Styles elements : https://github.com/Kunzisoft/Android-SwitchDateTimePicker/blob/master/switchdatetime/src/main/res/values/styles.xml
97 |
98 | #### AlertStyle
99 | To customize the AlertDialog that is shown, use :
100 | `void setAlertStyle(@StyleRes int styleId)`
101 |
102 | ### Sample
103 | You can see
104 | https://github.com/J-Jamet/Android-SwitchDateTimePicker/blob/master/sample/src/main/java/com/kunzisoft/switchdatetimesample/Sample.java
105 | for complete sample.
106 | ```
107 | // Initialize
108 | SwitchDateTimeDialogFragment dateTimeDialogFragment = SwitchDateTimeDialogFragment.newInstance(
109 | "Title example",
110 | "OK",
111 | "Cancel"
112 | );
113 |
114 | // Assign values
115 | dateTimeDialogFragment.startAtCalendarView();
116 | dateTimeDialogFragment.set24HoursMode(true);
117 | dateTimeDialogFragment.setMinimumDateTime(new GregorianCalendar(2015, Calendar.JANUARY, 1).getTime());
118 | dateTimeDialogFragment.setMaximumDateTime(new GregorianCalendar(2025, Calendar.DECEMBER, 31).getTime());
119 | dateTimeDialogFragment.setDefaultDateTime(new GregorianCalendar(2017, Calendar.MARCH, 4, 15, 20).getTime());
120 |
121 | // Define new day and month format
122 | try {
123 | dateTimeDialogFragment.setSimpleDateMonthAndDayFormat(new SimpleDateFormat("dd MMMM", Locale.getDefault()));
124 | } catch (SwitchDateTimeDialogFragment.SimpleDateMonthAndDayFormatException e) {
125 | Log.e(TAG, e.getMessage());
126 | }
127 |
128 | // Set listener
129 | dateTimeDialogFragment.setOnButtonClickListener(new SwitchDateTimeDialogFragment.OnButtonClickListener() {
130 | @Override
131 | public void onPositiveButtonClick(Date date) {
132 | // Date is get on positive button click
133 | // Do something
134 | }
135 |
136 | @Override
137 | public void onNegativeButtonClick(Date date) {
138 | // Date is get on negative button click
139 | }
140 | });
141 |
142 | // Show
143 | dateTimeDialogFragment.show(getSupportFragmentManager(), "dialog_time");
144 | ```
145 |
146 | #### Neutral button
147 |
148 |
149 |
150 | To use with a neutral button, initialize with another parameter and implement the *OnButtonWithNeutralClickListener* :
151 | ```
152 | SwitchDateTimeDialogFragment dateTimeDialogFragment = SwitchDateTimeDialogFragment.newInstance(
153 | "Title example",
154 | "OK",
155 | "Cancel",
156 | "Clean"
157 | );
158 |
159 | dateTimeFragment.setOnButtonClickListener(new SwitchDateTimeDialogFragment.OnButtonWithNeutralClickListener() {
160 | @Override
161 | public void onPositiveButtonClick(Date date) {
162 | }
163 |
164 | @Override
165 | public void onNegativeButtonClick(Date date) {
166 | }
167 |
168 | @Override
169 | public void onNeutralButtonClick(Date date) {
170 | }
171 | });
172 | ```
173 |
174 | ## Bonus
175 | You can follow the project live on https://www.livecoding.tv/kunzisoft/
176 |
177 | ## License
178 |
179 | Copyright (c) 2016 JAMET Jeremy
180 |
181 | Licensed under the Apache License, Version 2.0 (the "License");
182 | you may not use this file except in compliance with the License.
183 | You may obtain a copy of the License at
184 |
185 | http://www.apache.org/licenses/LICENSE-2.0
186 |
187 | Unless required by applicable law or agreed to in writing, software
188 | distributed under the License is distributed on an "AS IS" BASIS,
189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190 | See the License for the specific language governing permissions and
191 | limitations under the License.
192 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/java/com/kunzisoft/switchdatetime/time/widget/TimeAmPmCirclesView.java:
--------------------------------------------------------------------------------
1 | package com.kunzisoft.switchdatetime.time.widget;
2 | /*
3 | * Copyright (C) 2013 The Android Open Source Project
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | import android.content.Context;
19 | import android.content.res.Resources;
20 | import android.content.res.TypedArray;
21 | import android.graphics.Canvas;
22 | import android.graphics.Color;
23 | import android.graphics.Paint;
24 | import android.graphics.Paint.Align;
25 | import android.graphics.Typeface;
26 | import android.util.AttributeSet;
27 | import android.util.Log;
28 | import android.view.View;
29 |
30 | import com.kunzisoft.switchdatetime.R;
31 | import com.kunzisoft.switchdatetime.time.SwitchTimePicker;
32 |
33 | import java.text.DateFormatSymbols;
34 |
35 | /**
36 | * Draw the two smaller AM and PM circles next to where the larger circle will be.
37 | */
38 | public class TimeAmPmCirclesView extends View {
39 | private static final String TAG = "AmPmCirclesView";
40 |
41 | // Alpha level of blue color for selected circle.
42 | private static final int SELECTED_ALPHA = 51;
43 | // Alpha level of blue color for pressed circle.
44 | private static final int PRESSED_ALPHA = 175;
45 |
46 | private final Paint mPaint = new Paint();
47 | private int mBackgroundColor = Color.WHITE;
48 | private int mAmPmTextColor = Color.BLACK;
49 | private int mSelectBackgroundColor = Color.BLUE;
50 | private boolean mInverseSelectedColors = false;
51 | private float mCircleRadiusMultiplier;
52 | private float mAmPmCircleRadiusMultiplier;
53 | private String mAmText;
54 | private String mPmText;
55 | private boolean mIsInitialized;
56 |
57 | private static final int AM = SwitchTimePicker.AM;
58 | private static final int PM = SwitchTimePicker.PM;
59 |
60 | private boolean mDrawValuesReady;
61 | private int mAmPmCircleRadius;
62 | private int mAmXCenter;
63 | private int mPmXCenter;
64 | private int mAmPmYCenter;
65 | private int mAmOrPm;
66 | private int mAmOrPmPressed;
67 |
68 | public TimeAmPmCirclesView(Context context) {
69 | this(context, null, 0);
70 | }
71 |
72 | public TimeAmPmCirclesView(Context context, AttributeSet attrs) {
73 | this(context, attrs, 0);
74 | }
75 |
76 | public TimeAmPmCirclesView(Context context, AttributeSet attrs, int defStyleAttr) {
77 | super(context, attrs, defStyleAttr);
78 |
79 | mIsInitialized = false;
80 |
81 | TypedArray switchTimeColorTypedArray = getContext().obtainStyledAttributes(attrs, R.styleable.TimeAmPmCirclesView);
82 | setCircleColor(switchTimeColorTypedArray.getColor(R.styleable.TimeAmPmCirclesView_timeAmPmBackgroundColor, mBackgroundColor));
83 | setSelectCircleColor(switchTimeColorTypedArray.getColor(R.styleable.TimeAmPmCirclesView_timeAmPmSelectBackgroundColor, mSelectBackgroundColor));
84 | setAmPmTextColor(switchTimeColorTypedArray.getColor(R.styleable.TimeAmPmCirclesView_timeAmPmTextColor, mAmPmTextColor));
85 | setInverseSelectedColors(switchTimeColorTypedArray.getBoolean(R.styleable.TimeAmPmCirclesView_timeAmPmHighlightSelected, mInverseSelectedColors));
86 | switchTimeColorTypedArray.recycle();
87 | }
88 |
89 | public void initialize(Context context, int amOrPm) {
90 | if (mIsInitialized) {
91 | Log.e(TAG, "AmPmCirclesView may only be initialized once.");
92 | return;
93 | }
94 |
95 | Resources res = context.getResources();
96 |
97 | String typefaceFamily = res.getString(R.string.sans_serif);
98 | Typeface tf = Typeface.create(typefaceFamily, Typeface.NORMAL);
99 | mPaint.setTypeface(tf);
100 | mPaint.setAntiAlias(true);
101 | mPaint.setTextAlign(Align.CENTER);
102 |
103 | mCircleRadiusMultiplier =
104 | Float.parseFloat(res.getString(R.string.circle_radius_multiplier));
105 | mAmPmCircleRadiusMultiplier =
106 | Float.parseFloat(res.getString(R.string.ampm_circle_radius_multiplier));
107 | String[] amPmTexts = new DateFormatSymbols().getAmPmStrings();
108 | mAmText = amPmTexts[0];
109 | mPmText = amPmTexts[1];
110 |
111 | setAmOrPm(amOrPm);
112 | mAmOrPmPressed = -1;
113 |
114 | mIsInitialized = true;
115 | }
116 |
117 | /**
118 | * Set to AM or PM mode
119 | * @param amOrPm AM or PM id
120 | */
121 | public void setAmOrPm(int amOrPm) {
122 | mAmOrPm = amOrPm;
123 | }
124 |
125 | /**
126 | * Set to AM or PM mode when pressed
127 | * @param amOrPmPressed AM or PM pressed
128 | */
129 | public void setAmOrPmPressed(int amOrPmPressed) {
130 | mAmOrPmPressed = amOrPmPressed;
131 | }
132 |
133 | /**
134 | * Calculate whether the coordinates are touching the AM or PM circle.
135 | */
136 | public int getIsTouchingAmOrPm(float xCoord, float yCoord) {
137 | if (!mDrawValuesReady) {
138 | return -1;
139 | }
140 |
141 | int squaredYDistance = (int) ((yCoord - mAmPmYCenter) * (yCoord - mAmPmYCenter));
142 |
143 | int distanceToAmCenter =
144 | (int) Math.sqrt((xCoord - mAmXCenter) * (xCoord - mAmXCenter) + squaredYDistance);
145 | if (distanceToAmCenter <= mAmPmCircleRadius) {
146 | return AM;
147 | }
148 |
149 | int distanceToPmCenter =
150 | (int) Math.sqrt((xCoord - mPmXCenter) * (xCoord - mPmXCenter) + squaredYDistance);
151 | if (distanceToPmCenter <= mAmPmCircleRadius) {
152 | return PM;
153 | }
154 |
155 | // Neither was close enough.
156 | return -1;
157 | }
158 |
159 | @Override
160 | public void onDraw(Canvas canvas) {
161 | int viewWidth = getWidth();
162 | if (viewWidth == 0 || !mIsInitialized) {
163 | return;
164 | }
165 |
166 | if (!mDrawValuesReady) {
167 | int layoutXCenter = getWidth() / 2;
168 | int layoutYCenter = getHeight() / 2;
169 | int circleRadius =
170 | (int) (Math.min(layoutXCenter, layoutYCenter) * mCircleRadiusMultiplier);
171 | mAmPmCircleRadius = (int) (circleRadius * mAmPmCircleRadiusMultiplier);
172 | int textSize = mAmPmCircleRadius * 3 / 4;
173 | mPaint.setTextSize(textSize);
174 |
175 | // Line up the vertical center of the AM/PM circles with the bottom of the main circle.
176 | mAmPmYCenter = layoutYCenter - mAmPmCircleRadius / 2 + circleRadius;
177 | // Line up the horizontal edges of the AM/PM circles with the horizontal edges
178 | // of the main circle.
179 | mAmXCenter = layoutXCenter - circleRadius + mAmPmCircleRadius;
180 | mPmXCenter = layoutXCenter + circleRadius - mAmPmCircleRadius;
181 |
182 | mDrawValuesReady = true;
183 | }
184 |
185 | // We'll need to draw either a lighter blue (for selection), a darker blue (for touching)
186 | // or white (for not selected).
187 | int amColor = mBackgroundColor;
188 | int amAlpha = 255;
189 | int pmColor = mBackgroundColor;
190 | int pmAlpha = 255;
191 |
192 | if (mInverseSelectedColors) {
193 | if (mAmOrPm == AM) {
194 | pmColor = mSelectBackgroundColor;
195 | pmAlpha = SELECTED_ALPHA;
196 | } else if (mAmOrPm == PM) {
197 | amColor = mSelectBackgroundColor;
198 | amAlpha = SELECTED_ALPHA;
199 | }
200 | if (mAmOrPmPressed == AM) {
201 | pmColor = mSelectBackgroundColor;
202 | pmAlpha = PRESSED_ALPHA;
203 | } else if (mAmOrPmPressed == PM) {
204 | amColor = mSelectBackgroundColor;
205 | amAlpha = PRESSED_ALPHA;
206 | }
207 | } else {
208 | if (mAmOrPm == AM) {
209 | amColor = mSelectBackgroundColor;
210 | amAlpha = SELECTED_ALPHA;
211 | } else if (mAmOrPm == PM) {
212 | pmColor = mSelectBackgroundColor;
213 | pmAlpha = SELECTED_ALPHA;
214 | }
215 | if (mAmOrPmPressed == AM) {
216 | amColor = mSelectBackgroundColor;
217 | amAlpha = PRESSED_ALPHA;
218 | } else if (mAmOrPmPressed == PM) {
219 | pmColor = mSelectBackgroundColor;
220 | pmAlpha = PRESSED_ALPHA;
221 | }
222 | }
223 |
224 | // Draw the two circles.
225 | mPaint.setColor(amColor);
226 | mPaint.setAlpha(amAlpha);
227 | canvas.drawCircle(mAmXCenter, mAmPmYCenter, mAmPmCircleRadius, mPaint);
228 | mPaint.setColor(pmColor);
229 | mPaint.setAlpha(pmAlpha);
230 | canvas.drawCircle(mPmXCenter, mAmPmYCenter, mAmPmCircleRadius, mPaint);
231 |
232 | // Draw the AM/PM texts on top.
233 | mPaint.setColor(mAmPmTextColor);
234 | int textYCenter = mAmPmYCenter - (int) (mPaint.descent() + mPaint.ascent()) / 2;
235 | canvas.drawText(mAmText, mAmXCenter, textYCenter, mPaint);
236 | canvas.drawText(mPmText, mPmXCenter, textYCenter, mPaint);
237 | }
238 |
239 | /**
240 | * Get circle background color
241 | * @return background color
242 | */
243 | public int getCircleColor() {
244 | return mBackgroundColor;
245 | }
246 |
247 | /**
248 | * Assign circle background color
249 | * @param backgroundColor background color
250 | */
251 | public void setCircleColor(int backgroundColor) {
252 | this.mBackgroundColor = backgroundColor;
253 | }
254 |
255 | /**
256 | * Get AP/PM text color
257 | * @return text color
258 | */
259 | public int getAmPmTextColor() {
260 | return mAmPmTextColor;
261 | }
262 |
263 | /**
264 | * Assign AP/PM text color
265 | * @param amPmTextColor text color
266 | */
267 | public void setAmPmTextColor(int amPmTextColor) {
268 | this.mAmPmTextColor = amPmTextColor;
269 | }
270 |
271 | /**
272 | * Get select background color
273 | * @return text color
274 | */
275 | public int getSelectCircleColor() {
276 | return mSelectBackgroundColor;
277 | }
278 |
279 | /**
280 | * Set select background color
281 | * @param selectBackgroundColor background color
282 | */
283 | public void setSelectCircleColor(int selectBackgroundColor) {
284 | this.mSelectBackgroundColor = selectBackgroundColor;
285 | }
286 |
287 | /**
288 | * Determine if AM / PM selected and unselected colors must be inverted
289 | * @param inverseColors true to inverse color
290 | */
291 | public void setInverseSelectedColors(boolean inverseColors) {
292 | this.mInverseSelectedColors = inverseColors;
293 | }
294 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2017 Jeremy JAMET
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/switchdatetime/src/main/java/com/kunzisoft/switchdatetime/time/widget/TimeRadialNumbersView.java:
--------------------------------------------------------------------------------
1 | package com.kunzisoft.switchdatetime.time.widget;
2 | /*
3 | * Copyright (C) 2013 The Android Open Source Project
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | import android.animation.Keyframe;
19 | import android.animation.ObjectAnimator;
20 | import android.animation.PropertyValuesHolder;
21 | import android.animation.ValueAnimator;
22 | import android.content.Context;
23 | import android.content.res.Resources;
24 | import android.content.res.TypedArray;
25 | import android.graphics.Canvas;
26 | import android.graphics.Color;
27 | import android.graphics.Paint;
28 | import android.graphics.Paint.Align;
29 | import android.graphics.Typeface;
30 | import android.util.AttributeSet;
31 | import android.util.Log;
32 | import android.view.View;
33 |
34 | import com.kunzisoft.switchdatetime.R;
35 |
36 | /**
37 | * A view to show a series of numbers in a circular pattern.
38 | */
39 | public class TimeRadialNumbersView extends View {
40 | private final static String TAG = "RadialTextsView";
41 |
42 | private final Paint mPaint = new Paint();
43 |
44 | private boolean mDrawValuesReady;
45 | private boolean mIsInitialized;
46 |
47 | private Typeface mTypefaceLight;
48 | private Typeface mTypefaceRegular;
49 | private String[] mTexts;
50 | private String[] mInnerTexts;
51 | private boolean mIs24HourMode;
52 | private boolean mHasInnerCircle;
53 | private float mCircleRadiusMultiplier;
54 | private float mAmPmCircleRadiusMultiplier;
55 | private float mNumbersRadiusMultiplier;
56 | private float mInnerNumbersRadiusMultiplier;
57 | private float mTextSizeMultiplier;
58 | private float mInnerTextSizeMultiplier;
59 |
60 | private int mXCenter;
61 | private int mYCenter;
62 | private float mCircleRadius;
63 | private boolean mTextGridValuesDirty;
64 | private float mTextSize;
65 | private float mInnerTextSize;
66 | private float[] mTextGridHeights;
67 | private float[] mTextGridWidths;
68 | private float[] mInnerTextGridHeights;
69 | private float[] mInnerTextGridWidths;
70 |
71 | private float mAnimationRadiusMultiplier;
72 | private float mTransitionMidRadiusMultiplier;
73 | private float mTransitionEndRadiusMultiplier;
74 | ObjectAnimator mDisappearAnimator;
75 | ObjectAnimator mReappearAnimator;
76 | private InvalidateUpdateListener mInvalidateUpdateListener;
77 |
78 |
79 | public TimeRadialNumbersView(Context context) {
80 | this(context, null, 0);
81 | }
82 |
83 | public TimeRadialNumbersView(Context context, AttributeSet attrs) {
84 | this(context, attrs, 0);
85 | }
86 |
87 | public TimeRadialNumbersView(Context context, AttributeSet attrs, int defStyleAttr) {
88 | super(context, attrs, defStyleAttr);
89 |
90 | mIsInitialized = false;
91 |
92 | TypedArray switchTimeColorTypedArray = getContext().obtainStyledAttributes(attrs, R.styleable.TimeRadialNumbersView);
93 | setNumbersColor(switchTimeColorTypedArray.getColor(R.styleable.TimeRadialNumbersView_timeCircularNumbersColor, Color.BLACK));
94 | switchTimeColorTypedArray.recycle();
95 |
96 | mPaint.setAntiAlias(true);
97 | }
98 |
99 | public void initialize(Resources res, String[] texts, String[] innerTexts,
100 | boolean is24HourMode, boolean disappearsOut) {
101 | if (mIsInitialized) {
102 | Log.e(TAG, "This RadialTextsView may only be initialized once.");
103 | return;
104 | }
105 |
106 | // Set up the paint.
107 | String typefaceFamily = res.getString(R.string.radial_numbers_typeface);
108 | mTypefaceLight = Typeface.create(typefaceFamily, Typeface.NORMAL);
109 | String typefaceFamilyRegular = res.getString(R.string.sans_serif);
110 | mTypefaceRegular = Typeface.create(typefaceFamilyRegular, Typeface.NORMAL);
111 | mPaint.setAntiAlias(true);
112 | mPaint.setTextAlign(Align.CENTER);
113 |
114 | mTexts = texts;
115 | mInnerTexts = innerTexts;
116 | mIs24HourMode = is24HourMode;
117 | mHasInnerCircle = (innerTexts != null);
118 |
119 | // Calculate the radius for the main circle.
120 | if (is24HourMode) {
121 | mCircleRadiusMultiplier = Float.parseFloat(
122 | res.getString(R.string.circle_radius_multiplier_24HourMode));
123 | } else {
124 | mCircleRadiusMultiplier = Float.parseFloat(
125 | res.getString(R.string.circle_radius_multiplier));
126 | mAmPmCircleRadiusMultiplier =
127 | Float.parseFloat(res.getString(R.string.ampm_circle_radius_multiplier));
128 | }
129 |
130 | // Initialize the widths and heights of the grid, and calculate the values for the numbers.
131 | mTextGridHeights = new float[7];
132 | mTextGridWidths = new float[7];
133 | if (mHasInnerCircle) {
134 | mNumbersRadiusMultiplier = Float.parseFloat(
135 | res.getString(R.string.numbers_radius_multiplier_outer));
136 | mTextSizeMultiplier = Float.parseFloat(
137 | res.getString(R.string.text_size_multiplier_outer));
138 | mInnerNumbersRadiusMultiplier = Float.parseFloat(
139 | res.getString(R.string.numbers_radius_multiplier_inner));
140 | mInnerTextSizeMultiplier = Float.parseFloat(
141 | res.getString(R.string.text_size_multiplier_inner));
142 |
143 | mInnerTextGridHeights = new float[7];
144 | mInnerTextGridWidths = new float[7];
145 | } else {
146 | mNumbersRadiusMultiplier = Float.parseFloat(
147 | res.getString(R.string.numbers_radius_multiplier_normal));
148 | mTextSizeMultiplier = Float.parseFloat(
149 | res.getString(R.string.text_size_multiplier_normal));
150 | }
151 |
152 | mAnimationRadiusMultiplier = 1;
153 | mTransitionMidRadiusMultiplier = 1f + (0.05f * (disappearsOut ? -1 : 1));
154 | mTransitionEndRadiusMultiplier = 1f + (0.3f * (disappearsOut ? 1 : -1));
155 | mInvalidateUpdateListener = new InvalidateUpdateListener();
156 |
157 | mTextGridValuesDirty = true;
158 | mIsInitialized = true;
159 | }
160 |
161 | /**
162 | * Allows for smoother animation.
163 | */
164 | @Override
165 | public boolean hasOverlappingRendering() {
166 | return false;
167 | }
168 |
169 | /**
170 | * Used by the animation to move the numbers in and out.
171 | */
172 | public void setAnimationRadiusMultiplier(float animationRadiusMultiplier) {
173 | mAnimationRadiusMultiplier = animationRadiusMultiplier;
174 | mTextGridValuesDirty = true;
175 | }
176 |
177 | @Override
178 | public void onDraw(Canvas canvas) {
179 | int viewWidth = getWidth();
180 | if (viewWidth == 0 || !mIsInitialized) {
181 | return;
182 | }
183 |
184 | if (!mDrawValuesReady) {
185 | mXCenter = getWidth() / 2;
186 | mYCenter = getHeight() / 2;
187 | mCircleRadius = Math.min(mXCenter, mYCenter) * mCircleRadiusMultiplier;
188 | if (!mIs24HourMode) {
189 | // We'll need to draw the AM/PM circles, so the main circle will need to have
190 | // a slightly higher center. To keep the entire view centered vertically, we'll
191 | // have to push it up by half the radius of the AM/PM circles.
192 | float amPmCircleRadius = mCircleRadius * mAmPmCircleRadiusMultiplier;
193 | mYCenter -= amPmCircleRadius / 2;
194 | }
195 |
196 | mTextSize = mCircleRadius * mTextSizeMultiplier;
197 | if (mHasInnerCircle) {
198 | mInnerTextSize = mCircleRadius * mInnerTextSizeMultiplier;
199 | }
200 |
201 | // Because the text positions will be static, pre-render the animations.
202 | renderAnimations();
203 |
204 | mTextGridValuesDirty = true;
205 | mDrawValuesReady = true;
206 | }
207 |
208 | // Calculate the text positions, but only if they've changed since the last onDraw.
209 | if (mTextGridValuesDirty) {
210 | float numbersRadius =
211 | mCircleRadius * mNumbersRadiusMultiplier * mAnimationRadiusMultiplier;
212 |
213 | // Calculate the positions for the 12 numbers in the main circle.
214 | calculateGridSizes(numbersRadius, mXCenter, mYCenter,
215 | mTextSize, mTextGridHeights, mTextGridWidths);
216 | if (mHasInnerCircle) {
217 | // If we have an inner circle, calculate those positions too.
218 | float innerNumbersRadius =
219 | mCircleRadius * mInnerNumbersRadiusMultiplier * mAnimationRadiusMultiplier;
220 | calculateGridSizes(innerNumbersRadius, mXCenter, mYCenter,
221 | mInnerTextSize, mInnerTextGridHeights, mInnerTextGridWidths);
222 | }
223 | mTextGridValuesDirty = false;
224 | }
225 |
226 | // Draw the texts in the pre-calculated positions.
227 | drawTexts(canvas, mTextSize, mTypefaceLight, mTexts, mTextGridWidths, mTextGridHeights);
228 | if (mHasInnerCircle) {
229 | drawTexts(canvas, mInnerTextSize, mTypefaceRegular, mInnerTexts,
230 | mInnerTextGridWidths, mInnerTextGridHeights);
231 | }
232 | }
233 |
234 | /**
235 | * Using the trigonometric Unit Circle, calculate the positions that the text will need to be
236 | * drawn at based on the specified circle radius. Place the values in the textGridHeights and
237 | * textGridWidths parameters.
238 | */
239 | private void calculateGridSizes(float numbersRadius, float xCenter, float yCenter,
240 | float textSize, float[] textGridHeights, float[] textGridWidths) {
241 | /*
242 | * The numbers need to be drawn in a 7x7 grid, representing the points on the Unit Circle.
243 | */
244 | float offset1 = numbersRadius;
245 | // cos(30) = a / r => r * cos(30) = a => r * √3/2 = a
246 | float offset2 = numbersRadius * ((float) Math.sqrt(3)) / 2f;
247 | // sin(30) = o / r => r * sin(30) = o => r / 2 = a
248 | float offset3 = numbersRadius / 2f;
249 | mPaint.setTextSize(textSize);
250 | // We'll need yTextBase to be slightly lower to account for the text's baseline.
251 | yCenter -= (mPaint.descent() + mPaint.ascent()) / 2;
252 |
253 | textGridHeights[0] = yCenter - offset1;
254 | textGridWidths[0] = xCenter - offset1;
255 | textGridHeights[1] = yCenter - offset2;
256 | textGridWidths[1] = xCenter - offset2;
257 | textGridHeights[2] = yCenter - offset3;
258 | textGridWidths[2] = xCenter - offset3;
259 | textGridHeights[3] = yCenter;
260 | textGridWidths[3] = xCenter;
261 | textGridHeights[4] = yCenter + offset3;
262 | textGridWidths[4] = xCenter + offset3;
263 | textGridHeights[5] = yCenter + offset2;
264 | textGridWidths[5] = xCenter + offset2;
265 | textGridHeights[6] = yCenter + offset1;
266 | textGridWidths[6] = xCenter + offset1;
267 | }
268 |
269 | /**
270 | * Draw the 12 text values at the positions specified by the textGrid parameters.
271 | */
272 | private void drawTexts(Canvas canvas, float textSize, Typeface typeface, String[] texts,
273 | float[] textGridWidths, float[] textGridHeights) {
274 | mPaint.setTextSize(textSize);
275 | mPaint.setTypeface(typeface);
276 | canvas.drawText(texts[0], textGridWidths[3], textGridHeights[0], mPaint);
277 | canvas.drawText(texts[1], textGridWidths[4], textGridHeights[1], mPaint);
278 | canvas.drawText(texts[2], textGridWidths[5], textGridHeights[2], mPaint);
279 | canvas.drawText(texts[3], textGridWidths[6], textGridHeights[3], mPaint);
280 | canvas.drawText(texts[4], textGridWidths[5], textGridHeights[4], mPaint);
281 | canvas.drawText(texts[5], textGridWidths[4], textGridHeights[5], mPaint);
282 | canvas.drawText(texts[6], textGridWidths[3], textGridHeights[6], mPaint);
283 | canvas.drawText(texts[7], textGridWidths[2], textGridHeights[5], mPaint);
284 | canvas.drawText(texts[8], textGridWidths[1], textGridHeights[4], mPaint);
285 | canvas.drawText(texts[9], textGridWidths[0], textGridHeights[3], mPaint);
286 | canvas.drawText(texts[10], textGridWidths[1], textGridHeights[2], mPaint);
287 | canvas.drawText(texts[11], textGridWidths[2], textGridHeights[1], mPaint);
288 | }
289 |
290 | /**
291 | * Render the animations for appearing and disappearing.
292 | */
293 | private void renderAnimations() {
294 | Keyframe kf0, kf1, kf2, kf3;
295 | float midwayPoint = 0.2f;
296 | int duration = 500;
297 |
298 | // Set up animator for disappearing.
299 | kf0 = Keyframe.ofFloat(0f, 1);
300 | kf1 = Keyframe.ofFloat(midwayPoint, mTransitionMidRadiusMultiplier);
301 | kf2 = Keyframe.ofFloat(1f, mTransitionEndRadiusMultiplier);
302 | PropertyValuesHolder radiusDisappear = PropertyValuesHolder.ofKeyframe(
303 | "animationRadiusMultiplier", kf0, kf1, kf2);
304 |
305 | kf0 = Keyframe.ofFloat(0f, 1f);
306 | kf1 = Keyframe.ofFloat(1f, 0f);
307 | PropertyValuesHolder fadeOut = PropertyValuesHolder.ofKeyframe("alpha", kf0, kf1);
308 |
309 | mDisappearAnimator = ObjectAnimator.ofPropertyValuesHolder(
310 | this, radiusDisappear, fadeOut).setDuration(duration);
311 | mDisappearAnimator.addUpdateListener(mInvalidateUpdateListener);
312 |
313 |
314 | // Set up animator for reappearing.
315 | float delayMultiplier = 0.25f;
316 | float transitionDurationMultiplier = 1f;
317 | float totalDurationMultiplier = transitionDurationMultiplier + delayMultiplier;
318 | int totalDuration = (int) (duration * totalDurationMultiplier);
319 | float delayPoint = (delayMultiplier * duration) / totalDuration;
320 | midwayPoint = 1 - (midwayPoint * (1 - delayPoint));
321 |
322 | kf0 = Keyframe.ofFloat(0f, mTransitionEndRadiusMultiplier);
323 | kf1 = Keyframe.ofFloat(delayPoint, mTransitionEndRadiusMultiplier);
324 | kf2 = Keyframe.ofFloat(midwayPoint, mTransitionMidRadiusMultiplier);
325 | kf3 = Keyframe.ofFloat(1f, 1);
326 | PropertyValuesHolder radiusReappear = PropertyValuesHolder.ofKeyframe(
327 | "animationRadiusMultiplier", kf0, kf1, kf2, kf3);
328 |
329 | kf0 = Keyframe.ofFloat(0f, 0f);
330 | kf1 = Keyframe.ofFloat(delayPoint, 0f);
331 | kf2 = Keyframe.ofFloat(1f, 1f);
332 | PropertyValuesHolder fadeIn = PropertyValuesHolder.ofKeyframe("alpha", kf0, kf1, kf2);
333 |
334 | mReappearAnimator = ObjectAnimator.ofPropertyValuesHolder(
335 | this, radiusReappear, fadeIn).setDuration(totalDuration);
336 | mReappearAnimator.addUpdateListener(mInvalidateUpdateListener);
337 | }
338 |
339 | public ObjectAnimator getDisappearAnimator() {
340 | if (!mIsInitialized || !mDrawValuesReady || mDisappearAnimator == null) {
341 | Log.e(TAG, "RadialTextView was not ready for animation.");
342 | return null;
343 | }
344 |
345 | return mDisappearAnimator;
346 | }
347 |
348 | public ObjectAnimator getReappearAnimator() {
349 | if (!mIsInitialized || !mDrawValuesReady || mReappearAnimator == null) {
350 | Log.e(TAG, "RadialTextView was not ready for animation.");
351 | return null;
352 | }
353 |
354 | return mReappearAnimator;
355 | }
356 |
357 | private class InvalidateUpdateListener implements ValueAnimator.AnimatorUpdateListener {
358 | @Override
359 | public void onAnimationUpdate(ValueAnimator animation) {
360 | TimeRadialNumbersView.this.invalidate();
361 | }
362 | }
363 |
364 | public int getNumbersColor() {
365 | return mPaint.getColor();
366 | }
367 |
368 | public void setNumbersColor(int color) {
369 | mPaint.setColor(color);
370 | }
371 | }
--------------------------------------------------------------------------------
/switchdatetime/src/main/java/com/kunzisoft/switchdatetime/time/widget/TimeRadialSelectorView.java:
--------------------------------------------------------------------------------
1 | package com.kunzisoft.switchdatetime.time.widget;
2 | /*
3 | * Copyright (C) 2013 The Android Open Source Project
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | import android.animation.Keyframe;
19 | import android.animation.ObjectAnimator;
20 | import android.animation.PropertyValuesHolder;
21 | import android.animation.ValueAnimator;
22 | import android.content.Context;
23 | import android.content.res.Resources;
24 | import android.content.res.TypedArray;
25 | import android.graphics.Canvas;
26 | import android.graphics.Color;
27 | import android.graphics.Paint;
28 | import android.util.AttributeSet;
29 | import android.util.Log;
30 | import android.view.View;
31 |
32 | import com.kunzisoft.switchdatetime.R;
33 |
34 | /**
35 | * View to show what number is selected. This will draw a blue circle over the number, with a blue
36 | * line coming from the center of the main circle to the edge of the blue selection.
37 | */
38 | public class TimeRadialSelectorView extends View {
39 | private static final String TAG = "RadialSelectorView";
40 |
41 | private final Paint mPaint = new Paint();
42 |
43 | private boolean mIsInitialized;
44 | private boolean mDrawValuesReady;
45 |
46 | private float mCircleRadiusMultiplier;
47 | private float mAmPmCircleRadiusMultiplier;
48 | private float mInnerNumbersRadiusMultiplier;
49 | private float mOuterNumbersRadiusMultiplier;
50 | private float mNumbersRadiusMultiplier;
51 | private float mSelectionRadiusMultiplier;
52 | private float mAnimationRadiusMultiplier;
53 | private boolean mIs24HourMode;
54 | private boolean mHasInnerCircle;
55 |
56 | private int mXCenter;
57 | private int mYCenter;
58 | private int mCircleRadius;
59 | private float mTransitionMidRadiusMultiplier;
60 | private float mTransitionEndRadiusMultiplier;
61 | private int mLineLength;
62 | private int mSelectionRadius;
63 | private InvalidateUpdateListener mInvalidateUpdateListener;
64 |
65 | private int mSelectionDegrees;
66 | private double mSelectionRadians;
67 | private boolean mForceDrawDot;
68 |
69 | public TimeRadialSelectorView(Context context) {
70 | this(context, null, 0);
71 | }
72 |
73 | public TimeRadialSelectorView(Context context, AttributeSet attrs) {
74 | this(context, attrs, 0);
75 | }
76 |
77 | public TimeRadialSelectorView(Context context, AttributeSet attrs, int defStyleAttr) {
78 | super(context, attrs, defStyleAttr);
79 |
80 | mIsInitialized = false;
81 |
82 | TypedArray switchTimeColorTypedArray = getContext().obtainStyledAttributes(attrs, R.styleable.TimeRadialSelectorView);
83 | setSelectorColor(switchTimeColorTypedArray.getColor(R.styleable.TimeRadialSelectorView_timeSelectorColor, Color.BLUE));
84 | switchTimeColorTypedArray.recycle();
85 |
86 | mPaint.setAntiAlias(true);
87 | }
88 |
89 | /**
90 | * Initialize this selector with the state of the picker.
91 | *
92 | * @param context Current context.
93 | * @param is24HourMode Whether the selector is in 24-hour mode, which will tell us
94 | * whether the circle's center is moved up slightly to make room for the AM/PM circles.
95 | * @param hasInnerCircle Whether we have both an inner and an outer circle of numbers
96 | * that may be selected. Should be true for 24-hour mode in the hours circle.
97 | * @param disappearsOut Whether the numbers' animation will have them disappearing out
98 | * or disappearing in.
99 | * @param selectionDegrees The initial degrees to be selected.
100 | * @param isInnerCircle Whether the initial selection is in the inner or outer circle.
101 | * Will be ignored when hasInnerCircle is false.
102 | */
103 | public void initialize(Context context, boolean is24HourMode, boolean hasInnerCircle,
104 | boolean disappearsOut, int selectionDegrees, boolean isInnerCircle) {
105 | if (mIsInitialized) {
106 | Log.e(TAG, "This RadialSelectorView may only be initialized once.");
107 | return;
108 | }
109 |
110 | Resources res = context.getResources();
111 |
112 | // Calculate values for the circle radius size.
113 | mIs24HourMode = is24HourMode;
114 | if (is24HourMode) {
115 | mCircleRadiusMultiplier = Float.parseFloat(
116 | res.getString(R.string.circle_radius_multiplier_24HourMode));
117 | } else {
118 | mCircleRadiusMultiplier = Float.parseFloat(
119 | res.getString(R.string.circle_radius_multiplier));
120 | mAmPmCircleRadiusMultiplier =
121 | Float.parseFloat(res.getString(R.string.ampm_circle_radius_multiplier));
122 | }
123 |
124 | // Calculate values for the radius size(s) of the numbers circle(s).
125 | mHasInnerCircle = hasInnerCircle;
126 | if (hasInnerCircle) {
127 | mInnerNumbersRadiusMultiplier =
128 | Float.parseFloat(res.getString(R.string.numbers_radius_multiplier_inner));
129 | mOuterNumbersRadiusMultiplier =
130 | Float.parseFloat(res.getString(R.string.numbers_radius_multiplier_outer));
131 | } else {
132 | mNumbersRadiusMultiplier =
133 | Float.parseFloat(res.getString(R.string.numbers_radius_multiplier_normal));
134 | }
135 | mSelectionRadiusMultiplier =
136 | Float.parseFloat(res.getString(R.string.selection_radius_multiplier));
137 |
138 | // Calculate values for the transition mid-way states.
139 | mAnimationRadiusMultiplier = 1;
140 | mTransitionMidRadiusMultiplier = 1f + (0.05f * (disappearsOut ? -1 : 1));
141 | mTransitionEndRadiusMultiplier = 1f + (0.3f * (disappearsOut ? 1 : -1));
142 | mInvalidateUpdateListener = new InvalidateUpdateListener();
143 |
144 | setSelection(selectionDegrees, isInnerCircle, false);
145 | mIsInitialized = true;
146 | }
147 |
148 | /**
149 | * Set the selection.
150 | *
151 | * @param selectionDegrees The degrees to be selected.
152 | * @param isInnerCircle Whether the selection should be in the inner circle or outer. Will be
153 | * ignored if hasInnerCircle was initialized to false.
154 | * @param forceDrawDot Whether to force the dot in the center of the selection circle to be
155 | * drawn. If false, the dot will be drawn only when the degrees is not a multiple of 30, i.e.
156 | * the selection is not on a visible number.
157 | */
158 | public void setSelection(int selectionDegrees, boolean isInnerCircle, boolean forceDrawDot) {
159 | mSelectionDegrees = selectionDegrees;
160 | mSelectionRadians = selectionDegrees * Math.PI / 180;
161 | mForceDrawDot = forceDrawDot;
162 |
163 | if (mHasInnerCircle) {
164 | if (isInnerCircle) {
165 | mNumbersRadiusMultiplier = mInnerNumbersRadiusMultiplier;
166 | } else {
167 | mNumbersRadiusMultiplier = mOuterNumbersRadiusMultiplier;
168 | }
169 | }
170 | }
171 |
172 | /**
173 | * Allows for smoother animations.
174 | */
175 | @Override
176 | public boolean hasOverlappingRendering() {
177 | return false;
178 | }
179 |
180 | /**
181 | * Set the multiplier for the radius. Will be used during animations to move in/out.
182 | */
183 | public void setAnimationRadiusMultiplier(float animationRadiusMultiplier) {
184 | mAnimationRadiusMultiplier = animationRadiusMultiplier;
185 | }
186 |
187 | public int getDegreesFromCoords(float pointX, float pointY, boolean forceLegal,
188 | final Boolean[] isInnerCircle) {
189 | if (!mDrawValuesReady) {
190 | return -1;
191 | }
192 |
193 | double hypotenuse = Math.sqrt(
194 | (pointY - mYCenter) * (pointY - mYCenter) +
195 | (pointX - mXCenter) * (pointX - mXCenter));
196 | // Check if we're outside the range
197 | if (mHasInnerCircle) {
198 | if (forceLegal) {
199 | // If we're told to force the coordinates to be legal, we'll set the isInnerCircle
200 | // boolean based based off whichever number the coordinates are closer to.
201 | int innerNumberRadius = (int) (mCircleRadius * mInnerNumbersRadiusMultiplier);
202 | int distanceToInnerNumber = (int) Math.abs(hypotenuse - innerNumberRadius);
203 | int outerNumberRadius = (int) (mCircleRadius * mOuterNumbersRadiusMultiplier);
204 | int distanceToOuterNumber = (int) Math.abs(hypotenuse - outerNumberRadius);
205 |
206 | isInnerCircle[0] = (distanceToInnerNumber <= distanceToOuterNumber);
207 | } else {
208 | // Otherwise, if we're close enough to either number (with the space between the
209 | // two allotted equally), set the isInnerCircle boolean as the closer one.
210 | // appropriately, but otherwise return -1.
211 | int minAllowedHypotenuseForInnerNumber =
212 | (int) (mCircleRadius * mInnerNumbersRadiusMultiplier) - mSelectionRadius;
213 | int maxAllowedHypotenuseForOuterNumber =
214 | (int) (mCircleRadius * mOuterNumbersRadiusMultiplier) + mSelectionRadius;
215 | int halfwayHypotenusePoint = (int) (mCircleRadius *
216 | ((mOuterNumbersRadiusMultiplier + mInnerNumbersRadiusMultiplier) / 2));
217 |
218 | if (hypotenuse >= minAllowedHypotenuseForInnerNumber &&
219 | hypotenuse <= halfwayHypotenusePoint) {
220 | isInnerCircle[0] = true;
221 | } else if (hypotenuse <= maxAllowedHypotenuseForOuterNumber &&
222 | hypotenuse >= halfwayHypotenusePoint) {
223 | isInnerCircle[0] = false;
224 | } else {
225 | return -1;
226 | }
227 | }
228 | } else {
229 | // If there's just one circle, we'll need to return -1 if:
230 | // we're not told to force the coordinates to be legal, and
231 | // the coordinates' distance to the number is within the allowed distance.
232 | if (!forceLegal) {
233 | int distanceToNumber = (int) Math.abs(hypotenuse - mLineLength);
234 | // The max allowed distance will be defined as the distance from the center of the
235 | // number to the edge of the circle.
236 | int maxAllowedDistance = (int) (mCircleRadius * (1 - mNumbersRadiusMultiplier));
237 | if (distanceToNumber > maxAllowedDistance) {
238 | return -1;
239 | }
240 | }
241 | }
242 |
243 |
244 | float opposite = Math.abs(pointY - mYCenter);
245 | double radians = Math.asin(opposite / hypotenuse);
246 | int degrees = (int) (radians * 180 / Math.PI);
247 |
248 | // Now we have to translate to the correct quadrant.
249 | boolean rightSide = (pointX > mXCenter);
250 | boolean topSide = (pointY < mYCenter);
251 | if (rightSide && topSide) {
252 | degrees = 90 - degrees;
253 | } else if (rightSide) {
254 | degrees = 90 + degrees;
255 | } else if (!topSide) {
256 | degrees = 270 - degrees;
257 | } else {
258 | degrees = 270 + degrees;
259 | }
260 | return degrees;
261 | }
262 |
263 | @Override
264 | public void onDraw(Canvas canvas) {
265 | int viewWidth = getWidth();
266 | if (viewWidth == 0 || !mIsInitialized) {
267 | return;
268 | }
269 |
270 | if (!mDrawValuesReady) {
271 | mXCenter = getWidth() / 2;
272 | mYCenter = getHeight() / 2;
273 | mCircleRadius = (int) (Math.min(mXCenter, mYCenter) * mCircleRadiusMultiplier);
274 |
275 | if (!mIs24HourMode) {
276 | // We'll need to draw the AM/PM circles, so the main circle will need to have
277 | // a slightly higher center. To keep the entire view centered vertically, we'll
278 | // have to push it up by half the radius of the AM/PM circles.
279 | int amPmCircleRadius = (int) (mCircleRadius * mAmPmCircleRadiusMultiplier);
280 | mYCenter -= amPmCircleRadius / 2;
281 | }
282 |
283 | mSelectionRadius = (int) (mCircleRadius * mSelectionRadiusMultiplier);
284 |
285 | mDrawValuesReady = true;
286 | }
287 |
288 | // Calculate the current radius at which to place the selection circle.
289 | mLineLength = (int) (mCircleRadius * mNumbersRadiusMultiplier * mAnimationRadiusMultiplier);
290 | int pointX = mXCenter + (int) (mLineLength * Math.sin(mSelectionRadians));
291 | int pointY = mYCenter - (int) (mLineLength * Math.cos(mSelectionRadians));
292 |
293 | // Draw the selection circle.
294 | mPaint.setAlpha(50);
295 | canvas.drawCircle(pointX, pointY, mSelectionRadius, mPaint);
296 |
297 | if (mForceDrawDot | mSelectionDegrees % 30 != 0) {
298 | // We're not on a direct tick (or we've been told to draw the dot anyway).
299 | mPaint.setAlpha(255);
300 | canvas.drawCircle(pointX, pointY, (mSelectionRadius * 2 / 7), mPaint);
301 | } else {
302 | // We're not drawing the dot, so shorten the line to only go as far as the edge of the
303 | // selection circle.
304 | int lineLength = mLineLength;
305 | lineLength -= mSelectionRadius;
306 | pointX = mXCenter + (int) (lineLength * Math.sin(mSelectionRadians));
307 | pointY = mYCenter - (int) (lineLength * Math.cos(mSelectionRadians));
308 | }
309 |
310 | // Draw the line from the center of the circle.
311 | mPaint.setAlpha(255);
312 | mPaint.setStrokeWidth(1);
313 | canvas.drawLine(mXCenter, mYCenter, pointX, pointY, mPaint);
314 | }
315 |
316 | public ObjectAnimator getDisappearAnimator() {
317 | if (!mIsInitialized || !mDrawValuesReady) {
318 | Log.e(TAG, "RadialSelectorView was not ready for animation.");
319 | return null;
320 | }
321 |
322 | Keyframe kf0, kf1, kf2;
323 | float midwayPoint = 0.2f;
324 | int duration = 500;
325 |
326 | kf0 = Keyframe.ofFloat(0f, 1);
327 | kf1 = Keyframe.ofFloat(midwayPoint, mTransitionMidRadiusMultiplier);
328 | kf2 = Keyframe.ofFloat(1f, mTransitionEndRadiusMultiplier);
329 | PropertyValuesHolder radiusDisappear = PropertyValuesHolder.ofKeyframe(
330 | "animationRadiusMultiplier", kf0, kf1, kf2);
331 |
332 | kf0 = Keyframe.ofFloat(0f, 1f);
333 | kf1 = Keyframe.ofFloat(1f, 0f);
334 | PropertyValuesHolder fadeOut = PropertyValuesHolder.ofKeyframe("alpha", kf0, kf1);
335 |
336 | ObjectAnimator disappearAnimator = ObjectAnimator.ofPropertyValuesHolder(
337 | this, radiusDisappear, fadeOut).setDuration(duration);
338 | disappearAnimator.addUpdateListener(mInvalidateUpdateListener);
339 |
340 | return disappearAnimator;
341 | }
342 |
343 | public ObjectAnimator getReappearAnimator() {
344 | if (!mIsInitialized || !mDrawValuesReady) {
345 | Log.e(TAG, "RadialSelectorView was not ready for animation.");
346 | return null;
347 | }
348 |
349 | Keyframe kf0, kf1, kf2, kf3;
350 | float midwayPoint = 0.2f;
351 | int duration = 500;
352 |
353 | // The time points are half of what they would normally be, because this animation is
354 | // staggered against the disappear so they happen seamlessly. The reappear starts
355 | // halfway into the disappear.
356 | float delayMultiplier = 0.25f;
357 | float transitionDurationMultiplier = 1f;
358 | float totalDurationMultiplier = transitionDurationMultiplier + delayMultiplier;
359 | int totalDuration = (int) (duration * totalDurationMultiplier);
360 | float delayPoint = (delayMultiplier * duration) / totalDuration;
361 | midwayPoint = 1 - (midwayPoint * (1 - delayPoint));
362 |
363 | kf0 = Keyframe.ofFloat(0f, mTransitionEndRadiusMultiplier);
364 | kf1 = Keyframe.ofFloat(delayPoint, mTransitionEndRadiusMultiplier);
365 | kf2 = Keyframe.ofFloat(midwayPoint, mTransitionMidRadiusMultiplier);
366 | kf3 = Keyframe.ofFloat(1f, 1);
367 | PropertyValuesHolder radiusReappear = PropertyValuesHolder.ofKeyframe(
368 | "animationRadiusMultiplier", kf0, kf1, kf2, kf3);
369 |
370 | kf0 = Keyframe.ofFloat(0f, 0f);
371 | kf1 = Keyframe.ofFloat(delayPoint, 0f);
372 | kf2 = Keyframe.ofFloat(1f, 1f);
373 | PropertyValuesHolder fadeIn = PropertyValuesHolder.ofKeyframe("alpha", kf0, kf1, kf2);
374 |
375 | ObjectAnimator reappearAnimator = ObjectAnimator.ofPropertyValuesHolder(
376 | this, radiusReappear, fadeIn).setDuration(totalDuration);
377 | reappearAnimator.addUpdateListener(mInvalidateUpdateListener);
378 | return reappearAnimator;
379 | }
380 |
381 | /**
382 | * We'll need to invalidate during the animation.
383 | */
384 | private class InvalidateUpdateListener implements ValueAnimator.AnimatorUpdateListener {
385 | @Override
386 | public void onAnimationUpdate(ValueAnimator animation) {
387 | TimeRadialSelectorView.this.invalidate();
388 | }
389 | }
390 |
391 | public int getSelectorColor() {
392 | return mPaint.getColor();
393 | }
394 |
395 | public void setSelectorColor(int color) {
396 | mPaint.setColor(color);
397 | }
398 | }
--------------------------------------------------------------------------------
/switchdatetime/src/main/java/com/kunzisoft/switchdatetime/SwitchDateTimeDialogFragment.java:
--------------------------------------------------------------------------------
1 | package com.kunzisoft.switchdatetime;
2 |
3 | import android.app.Dialog;
4 | import android.content.DialogInterface;
5 | import android.content.res.Configuration;
6 | import android.graphics.Color;
7 | import android.os.Bundle;
8 | import android.view.LayoutInflater;
9 | import android.view.View;
10 | import android.view.ViewGroup;
11 | import android.view.animation.Animation;
12 | import android.widget.ImageButton;
13 | import android.widget.TextView;
14 | import android.widget.ViewAnimator;
15 |
16 | import androidx.annotation.NonNull;
17 | import androidx.annotation.StyleRes;
18 | import androidx.appcompat.app.AlertDialog;
19 | import androidx.fragment.app.DialogFragment;
20 |
21 | import com.kunzisoft.switchdatetime.date.OnYearSelectedListener;
22 | import com.kunzisoft.switchdatetime.date.widget.ListPickerYearView;
23 | import com.kunzisoft.switchdatetime.time.SwitchTimePicker;
24 | import com.prolificinteractive.materialcalendarview.CalendarDay;
25 | import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
26 | import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;
27 |
28 | import java.text.SimpleDateFormat;
29 | import java.util.Calendar;
30 | import java.util.Date;
31 | import java.util.GregorianCalendar;
32 | import java.util.Locale;
33 | import java.util.TimeZone;
34 | import java.util.regex.Matcher;
35 | import java.util.regex.Pattern;
36 |
37 | /**
38 | * A fragment that displays a dialog window with Date and Time who can be selected by switch button
39 | *
40 | * @author J-Jamet
41 | */
42 | public class SwitchDateTimeDialogFragment extends DialogFragment {
43 |
44 | private static final String TAG = "SwitchDateTimeDialogFrg";
45 |
46 | private static final String STATE_DATETIME = "STATE_DATETIME";
47 | private static final String STATE_CURRENT_POSITION = "STATE_CURRENT_POSITION";
48 |
49 | private static final int UNDEFINED_POSITION = -1;
50 | private Calendar dateTimeCalendar = Calendar.getInstance();
51 | private Calendar minimumDateTime = new GregorianCalendar(1970, 1, 1);
52 | private Calendar maximumDateTime = new GregorianCalendar(2200, 1, 1);
53 | private TimeZone timeZone = TimeZone.getDefault();
54 |
55 | private static final String TAG_LABEL = "LABEL";
56 | private static final String TAG_POSITIVE_BUTTON = "POSITIVE_BUTTON";
57 | private static final String TAG_NEGATIVE_BUTTON = "NEGATIVE_BUTTON";
58 | private static final String TAG_NEUTRAL_BUTTON = "NEUTRAL_BUTTON";
59 | private static final String TAG_DEFAULT_LOCALE = "DEFAULT_LOCALE";
60 |
61 | private static final String DEFAULT_LOCALE = "en";
62 |
63 |
64 | private String mLabel;
65 | private String mPositiveButton;
66 | private String mDefaultLocale;
67 | private String mNegativeButton;
68 | private String mNeutralButton;
69 | private OnButtonClickListener mListener;
70 |
71 | private boolean is24HoursMode = false;
72 | private boolean highlightAMPMSelection = false;
73 | private int startAtPosition = UNDEFINED_POSITION;
74 | private int currentPosition = 0;
75 | private int alertStyleId;
76 |
77 | private SimpleDateFormat dayAndMonthSimpleDate;
78 | private SimpleDateFormat yearSimpleDate;
79 |
80 | private ViewAnimator viewSwitcher;
81 | private SwitchTimePicker timePicker;
82 | private MaterialCalendarView materialCalendarView;
83 | private ListPickerYearView listPickerYearView;
84 |
85 | private TextView monthAndDayHeaderValues;
86 | private TextView yearHeaderValues;
87 |
88 | private boolean blockAnimationIn;
89 | private boolean blockAnimationOut;
90 |
91 | /**
92 | * Create a new instance of SwitchDateTimeDialogFragment
93 | *
94 | * @param label Title of dialog
95 | * @param positiveButton Text for positive button
96 | * @param negativeButton Text for negative button
97 | * @return DialogFragment
98 | */
99 | public static SwitchDateTimeDialogFragment newInstance(String label, String positiveButton, String negativeButton) {
100 | return newInstance(label, positiveButton, negativeButton, null, DEFAULT_LOCALE);
101 | }
102 |
103 | /**
104 | * Create a new instance of SwitchDateTimeDialogFragment
105 | *
106 | * @param label Title of dialog
107 | * @param positiveButton Text for positive button
108 | * @param negativeButton Text for negative button
109 | * @param defaultLocale Text for default locale
110 | * @return DialogFragment
111 | */
112 | public static SwitchDateTimeDialogFragment newInstance(String label, String positiveButton, String negativeButton, String neutralButton, String defaultLocale) {
113 | SwitchDateTimeDialogFragment switchDateTimeDialogFragment = new SwitchDateTimeDialogFragment();
114 | // Add arguments
115 | Bundle args = new Bundle();
116 | args.putString(TAG_LABEL, label);
117 | args.putString(TAG_POSITIVE_BUTTON, positiveButton);
118 | args.putString(TAG_NEGATIVE_BUTTON, negativeButton);
119 | args.putString(TAG_DEFAULT_LOCALE, defaultLocale);
120 | if (neutralButton != null) {
121 | args.putString(TAG_NEUTRAL_BUTTON, neutralButton);
122 | }
123 | switchDateTimeDialogFragment.setArguments(args);
124 |
125 | return switchDateTimeDialogFragment;
126 | }
127 |
128 | /**
129 | * Set listener for actions
130 | *
131 | * @param onButtonClickListener Listener for click
132 | */
133 | public void setOnButtonClickListener(OnButtonClickListener onButtonClickListener) {
134 | this.mListener = onButtonClickListener;
135 | }
136 |
137 | @Override
138 | public void onSaveInstanceState(Bundle savedInstanceState) {
139 | // Save the current datetime and position
140 | savedInstanceState.putLong(STATE_DATETIME, dateTimeCalendar.getTimeInMillis());
141 | savedInstanceState.putInt(STATE_CURRENT_POSITION, currentPosition);
142 | timePicker.onSaveInstanceState(savedInstanceState);
143 |
144 | super.onSaveInstanceState(savedInstanceState);
145 | }
146 |
147 | @Override
148 | public @NonNull
149 | Dialog onCreateDialog(Bundle savedInstanceState) {
150 | super.onCreateDialog(savedInstanceState);
151 |
152 | assert getActivity() != null;
153 | assert getContext() != null;
154 |
155 | dateTimeCalendar.setTimeZone(timeZone);
156 |
157 | if (getArguments() != null) {
158 | mLabel = getArguments().getString(TAG_LABEL);
159 | mPositiveButton = getArguments().getString(TAG_POSITIVE_BUTTON);
160 | mNegativeButton = getArguments().getString(TAG_NEGATIVE_BUTTON);
161 | mNeutralButton = getArguments().getString(TAG_NEUTRAL_BUTTON);
162 | mDefaultLocale=getArguments().getString(TAG_DEFAULT_LOCALE);
163 | }
164 | setDefaultLocale(mDefaultLocale);
165 |
166 | if (savedInstanceState != null) {
167 | currentPosition = savedInstanceState.getInt(STATE_CURRENT_POSITION);
168 | dateTimeCalendar.setTime(new Date(savedInstanceState.getLong(STATE_DATETIME)));
169 | }
170 |
171 | // Throw exception if default select date isn't between minimumDateTime and maximumDateTime
172 | if (dateTimeCalendar.before(minimumDateTime) || dateTimeCalendar.after(maximumDateTime))
173 | throw new RuntimeException("Default date " + dateTimeCalendar.getTime() + " must be between "
174 | + minimumDateTime.getTime() + " and " + maximumDateTime.getTime());
175 |
176 | LayoutInflater inflater = LayoutInflater.from(getActivity());
177 | getActivity().getTheme().applyStyle(R.style.Theme_SwitchDateTime, false);
178 | View dateTimeLayout = inflater.inflate(R.layout.dialog_switch_datetime_picker,
179 | (ViewGroup) getActivity().findViewById(R.id.datetime_picker));
180 |
181 | // Set label
182 | TextView labelView = dateTimeLayout.findViewById(R.id.label);
183 | if (mLabel != null)
184 | labelView.setText(mLabel);
185 | else
186 | labelView.setText(getString(R.string.label_datetime_dialog));
187 |
188 | // Lock animation for fast clicks
189 | blockAnimationIn = false;
190 | blockAnimationOut = false;
191 | viewSwitcher = dateTimeLayout.findViewById(R.id.dateSwitcher);
192 | viewSwitcher.getInAnimation().setAnimationListener(new Animation.AnimationListener() {
193 | @Override
194 | public void onAnimationStart(Animation animation) {
195 | blockAnimationIn = true;
196 | }
197 |
198 | @Override
199 | public void onAnimationEnd(Animation animation) {
200 | blockAnimationIn = false;
201 | currentPosition = viewSwitcher.getDisplayedChild();
202 | }
203 |
204 | @Override
205 | public void onAnimationRepeat(Animation animation) {
206 | }
207 | });
208 | viewSwitcher.getOutAnimation().setAnimationListener(new Animation.AnimationListener() {
209 | @Override
210 | public void onAnimationStart(Animation animation) {
211 | blockAnimationOut = true;
212 | }
213 |
214 | @Override
215 | public void onAnimationEnd(Animation animation) {
216 | blockAnimationOut = false;
217 | }
218 |
219 | @Override
220 | public void onAnimationRepeat(Animation animation) {
221 | }
222 | });
223 |
224 | // Defined the start position
225 | if (startAtPosition != UNDEFINED_POSITION)
226 | currentPosition = startAtPosition;
227 | viewSwitcher.setDisplayedChild(currentPosition);
228 |
229 | // Button for switch between Hours/Minutes, Calendar and YearList
230 | ImageButton buttonSwitch = dateTimeLayout.findViewById(R.id.button_switch);
231 | buttonSwitch.setBackgroundColor(Color.TRANSPARENT);
232 | buttonSwitch.setOnClickListener(new View.OnClickListener() {
233 | @Override
234 | public void onClick(View view) {
235 | Utils.animLabelElement(view);
236 | if (!(blockAnimationIn && blockAnimationOut))
237 | viewSwitcher.showNext();
238 | }
239 | });
240 |
241 | // Values header hourOfDay minutes
242 | View timeHeaderValues = dateTimeLayout.findViewById(R.id.time_header_values);
243 | View.OnClickListener onTimeClickListener =
244 | new OnClickHeaderElementListener(HeaderViewsPosition.VIEW_HOURS_AND_MINUTES.getPosition());
245 | timeHeaderValues.setOnClickListener(onTimeClickListener);
246 | // Values header month day
247 | monthAndDayHeaderValues = dateTimeLayout.findViewById(R.id.date_picker_month_and_day);
248 | View.OnClickListener onMonthAndDayClickListener =
249 | new OnClickHeaderElementListener(HeaderViewsPosition.VIEW_MONTH_AND_DAY.getPosition());
250 | monthAndDayHeaderValues.setOnClickListener(onMonthAndDayClickListener);
251 | // Values header year
252 | yearHeaderValues = dateTimeLayout.findViewById(R.id.date_picker_year);
253 | View.OnClickListener onYearClickListener =
254 | new OnClickHeaderElementListener(HeaderViewsPosition.VIEW_YEAR.getPosition());
255 | yearHeaderValues.setOnClickListener(onYearClickListener);
256 |
257 | // Init simple date format if null
258 | if (dayAndMonthSimpleDate == null)
259 | dayAndMonthSimpleDate = new SimpleDateFormat("MMMM dd", Locale.getDefault());
260 | if (yearSimpleDate == null)
261 | yearSimpleDate = new SimpleDateFormat("yyyy", Locale.getDefault());
262 |
263 | dayAndMonthSimpleDate.setTimeZone(timeZone);
264 | yearSimpleDate.setTimeZone(timeZone);
265 |
266 | // Init headers
267 | yearHeaderValues.setText(yearSimpleDate.format(dateTimeCalendar.getTime()));
268 | monthAndDayHeaderValues.setText(dayAndMonthSimpleDate.format(dateTimeCalendar.getTime()));
269 |
270 | // Construct TimePicker
271 | SwitchTimePicker.OnTimeSelectedListener onTimeSelectedListener = new SwitchTimePicker.OnTimeSelectedListener() {
272 | @Override
273 | public void onTimeSelected(int hourOfDayTime, int minuteTime) {
274 | dateTimeCalendar.set(Calendar.HOUR_OF_DAY, hourOfDayTime);
275 | dateTimeCalendar.set(Calendar.MINUTE, minuteTime);
276 | }
277 | };
278 | // Init time with saved elements
279 | timePicker = new SwitchTimePicker(getContext(), onTimeSelectedListener, savedInstanceState);
280 | timePicker.setIs24HourMode(is24HoursMode);
281 | timePicker.setHighlightAMPMSelection(highlightAMPMSelection);
282 | timePicker.setHourOfDay(dateTimeCalendar.get(Calendar.HOUR_OF_DAY));
283 | timePicker.setMinute(dateTimeCalendar.get(Calendar.MINUTE));
284 | timePicker.onCreateView(dateTimeLayout, savedInstanceState);
285 | timePicker.setOnClickTimeListener(onTimeClickListener);
286 |
287 | // Construct DatePicker
288 | materialCalendarView = dateTimeLayout.findViewById(com.kunzisoft.switchdatetime.R.id.datePicker);
289 | materialCalendarView.state().edit()
290 | .setMinimumDate(CalendarDay.from(minimumDateTime))
291 | .setMaximumDate(CalendarDay.from(maximumDateTime))
292 | .commit();
293 | materialCalendarView.setCurrentDate(dateTimeCalendar);
294 | materialCalendarView.setDateSelected(dateTimeCalendar, true);
295 | materialCalendarView.setOnDateChangedListener(new OnDateSelectedListener() {
296 | @Override
297 | public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay calendarDay, boolean selected) {
298 | dateTimeCalendar.set(Calendar.YEAR, calendarDay.getYear());
299 | dateTimeCalendar.set(Calendar.MONTH, calendarDay.getMonth());
300 | dateTimeCalendar.set(Calendar.DAY_OF_MONTH, calendarDay.getDay());
301 | listPickerYearView.assignCurrentYear(calendarDay.getYear());
302 | yearHeaderValues.setText(yearSimpleDate.format(dateTimeCalendar.getTime()));
303 | monthAndDayHeaderValues.setText(dayAndMonthSimpleDate.format(dateTimeCalendar.getTime()));
304 | timePicker.clickHour();
305 | }
306 | });
307 | materialCalendarView.invalidate();
308 |
309 | // Construct YearPicker
310 | listPickerYearView = dateTimeLayout.findViewById(R.id.yearPicker);
311 | listPickerYearView.setMinYear(minimumDateTime.get(Calendar.YEAR));
312 | listPickerYearView.setMaxYear(maximumDateTime.get(Calendar.YEAR));
313 | listPickerYearView.assignCurrentYear(dateTimeCalendar.get(Calendar.YEAR));
314 | listPickerYearView.setDatePickerListener(new OnYearSelectedListener() {
315 | @Override
316 | public void onYearSelected(View view, int yearPicker) {
317 | dateTimeCalendar.set(Calendar.YEAR, yearPicker);
318 | yearHeaderValues.setText(yearSimpleDate.format(dateTimeCalendar.getTime()));
319 |
320 | // Unfortunately, we have lags here and thread isn't a solution :/
321 | materialCalendarView.setCurrentDate(dateTimeCalendar.getTime().getTime());
322 | materialCalendarView.setDateSelected(dateTimeCalendar, true);
323 | // For resolve bug of switch year
324 | materialCalendarView.goToNext();
325 | materialCalendarView.goToPrevious();
326 | }
327 | });
328 |
329 | // Assign buttons
330 | AlertDialog.Builder db;
331 | if (alertStyleId != 0) {
332 | db = new AlertDialog.Builder(getContext(), alertStyleId);
333 | } else {
334 | db = new AlertDialog.Builder(getContext());
335 | }
336 | db.setView(dateTimeLayout);
337 | if (mPositiveButton == null)
338 | mPositiveButton = getString(android.R.string.ok);
339 | db.setPositiveButton(mPositiveButton, new
340 | DialogInterface.OnClickListener() {
341 | public void onClick(DialogInterface dialog, int which) {
342 | if (mListener != null) {
343 | mListener.onPositiveButtonClick(dateTimeCalendar.getTime());
344 | }
345 | }
346 | });
347 | if (mNegativeButton == null)
348 | mNegativeButton = getString(android.R.string.cancel);
349 | db.setNegativeButton(mNegativeButton, new
350 | DialogInterface.OnClickListener() {
351 | public void onClick(DialogInterface dialog, int which) {
352 | // Close dialog
353 | if (mListener != null) {
354 | mListener.onNegativeButtonClick(dateTimeCalendar.getTime());
355 | }
356 | }
357 | });
358 | if (mNeutralButton != null) {
359 | db.setNeutralButton(mNeutralButton, new DialogInterface.OnClickListener() {
360 | @Override
361 | public void onClick(DialogInterface dialog, int which) {
362 | if (mListener != null) {
363 | if (mListener instanceof OnButtonWithNeutralClickListener)
364 | ((OnButtonWithNeutralClickListener) mListener).onNeutralButtonClick(dateTimeCalendar.getTime());
365 | }
366 | }
367 | });
368 | }
369 | return db.create();
370 | }
371 |
372 | private void setDefaultLocale(String mDefaultLocale) {
373 | Locale locale = new Locale(mDefaultLocale);
374 | Locale.setDefault(locale);
375 | Configuration config = new Configuration();
376 | config.locale = locale;
377 | getResources().updateConfiguration(config,getResources().getDisplayMetrics());
378 | }
379 |
380 | @Override
381 | public void onDismiss(DialogInterface dialog) {
382 | super.onDismiss(dialog);
383 | startAtPosition = UNDEFINED_POSITION;
384 | }
385 |
386 | /**
387 | * Define "Time" as the first view to show
388 | */
389 | public void startAtTimeView() {
390 | startAtPosition = HeaderViewsPosition.VIEW_HOURS_AND_MINUTES.getPosition();
391 | }
392 |
393 | /**
394 | * Define "Calendar" as the first view to show
395 | */
396 | public void startAtCalendarView() {
397 | startAtPosition = HeaderViewsPosition.VIEW_MONTH_AND_DAY.getPosition();
398 | }
399 |
400 | /**
401 | * Define "Year" as the first view to show
402 | */
403 | public void startAtYearView() {
404 | startAtPosition = HeaderViewsPosition.VIEW_YEAR.getPosition();
405 | }
406 |
407 | /**
408 | * Assign default year at start
409 | */
410 | public void setDefaultYear(int year) {
411 | this.dateTimeCalendar.set(Calendar.YEAR, year);
412 | }
413 |
414 | /**
415 | * @deprecated Does not change after launch
416 | * {@link #setDefaultYear(int)}
417 | */
418 | @Deprecated
419 | public void setYear(int year) {
420 | setDefaultYear(year);
421 | }
422 |
423 | /**
424 | * Assign default month at start (ex: Calendar.DECEMBER)
425 | *
426 | * @see Calendar
427 | */
428 | public void setDefaultMonth(int month) {
429 | this.dateTimeCalendar.set(Calendar.MONTH, month);
430 | }
431 |
432 | /**
433 | * @deprecated Does not change after launch
434 | * {@link #setDefaultMonth(int)}
435 | */
436 | @Deprecated
437 | public void setMonth(int month) {
438 | setDefaultMonth(month);
439 | }
440 |
441 | /**
442 | * Assign default day at start
443 | */
444 | public void setDefaultDay(int day) {
445 | this.dateTimeCalendar.set(Calendar.DAY_OF_MONTH, day);
446 | }
447 |
448 | /**
449 | * @deprecated Does not change after launch
450 | * {@link #setDefaultDay(int)}
451 | */
452 | @Deprecated
453 | public void setDay(int day) {
454 | setDefaultDay(day);
455 | }
456 |
457 | /**
458 | * Assign default hour of day (in 24 hours) at start
459 | */
460 | public void setDefaultHourOfDay(int hourOfDay) {
461 | this.dateTimeCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
462 | }
463 |
464 | /**
465 | * @deprecated Does not change after launch and 24 hours format
466 | * {@link #setDefaultHourOfDay(int)}
467 | */
468 | @Deprecated
469 | public void setHour(int hour) {
470 | setDefaultHourOfDay(hour);
471 | }
472 |
473 | /**
474 | * Assign default minute at start
475 | */
476 | public void setDefaultMinute(int minute) {
477 | this.dateTimeCalendar.set(Calendar.MINUTE, minute);
478 | }
479 |
480 | /**
481 | * @deprecated Does not change after launch
482 | * {@link #setDefaultMinute(int)}
483 | */
484 | @Deprecated
485 | public void setMinute(int minute) {
486 | setDefaultMinute(minute);
487 | }
488 |
489 | /**
490 | * Get current year
491 | */
492 | public int getYear() {
493 | return this.dateTimeCalendar.get(Calendar.YEAR);
494 | }
495 |
496 | /**
497 | * Get current month as Calendar.MONTH
498 | *
499 | * @see Calendar
500 | */
501 | public int getMonth() {
502 | return this.dateTimeCalendar.get(Calendar.MONTH);
503 | }
504 |
505 | /**
506 | * Get current day
507 | */
508 | public int getDay() {
509 | return this.dateTimeCalendar.get(Calendar.DAY_OF_MONTH);
510 | }
511 |
512 | /**
513 | * Get current hour of day (hour in 24 hours)
514 | */
515 | public int getHourOfDay() {
516 | return this.dateTimeCalendar.get(Calendar.HOUR_OF_DAY);
517 | }
518 |
519 | /**
520 | * Get current minute
521 | */
522 | public int getMinute() {
523 | return this.dateTimeCalendar.get(Calendar.MINUTE);
524 | }
525 |
526 | /**
527 | * Assign default DateTime at start
528 | */
529 | public void setDefaultDateTime(Date date) {
530 | this.dateTimeCalendar.setTime(date);
531 | }
532 |
533 | /**
534 | * Assign minimum DateTime who can be selected
535 | */
536 | public void setMinimumDateTime(Date date) {
537 | this.minimumDateTime.setTime(date);
538 | }
539 |
540 | /**
541 | * Assign maximum DateTime who can be selected
542 | */
543 | public void setMaximumDateTime(Date date) {
544 | this.maximumDateTime.setTime(date);
545 | }
546 |
547 | /**
548 | * Get minimum DateTime who can be selected
549 | */
550 | public Date getMinimumDateTime() {
551 | return minimumDateTime.getTime();
552 | }
553 |
554 | /**
555 | * Get maximum DateTime who can be selected
556 | */
557 | public Date getMaximumDateTime() {
558 | return maximumDateTime.getTime();
559 | }
560 |
561 | /**
562 | * Return default SimpleDateFormat for Month and Day
563 | */
564 | public SimpleDateFormat getSimpleDateMonthAndDayFormat() {
565 | return dayAndMonthSimpleDate;
566 | }
567 |
568 | /**
569 | * Assign a SimpleDateFormat like "d MMM" to show formatted DateTime
570 | *
571 | * @param simpleDateFormat Format to show month and day
572 | */
573 | public void setSimpleDateMonthAndDayFormat(SimpleDateFormat simpleDateFormat) throws SimpleDateMonthAndDayFormatException {
574 | Pattern patternMonthAndDay = Pattern.compile("(M|w|W|D|d|F|E|u|\\.|\\s)*");
575 | Matcher matcherMonthAndDay = patternMonthAndDay.matcher(simpleDateFormat.toPattern());
576 | if (!matcherMonthAndDay.matches()) {
577 | throw new SimpleDateMonthAndDayFormatException(simpleDateFormat.toPattern() + "isn't allowed for " + patternMonthAndDay.pattern());
578 | }
579 | this.dayAndMonthSimpleDate = simpleDateFormat;
580 | }
581 |
582 | /**
583 | * Define if time must be in 24 hours mode or in 12 hours, must be applied before "show"
584 | */
585 | public void set24HoursMode(boolean is24HoursMode) {
586 | this.is24HoursMode = is24HoursMode;
587 | }
588 |
589 | /**
590 | * Highlight AM or PM selected, by default AM or PM selected is not highlight. Only works if 24 hours mode is activated
591 | *
592 | * @param highlightAMPMSelection true to visually highlight selected item
593 | */
594 | public void setHighlightAMPMSelection(boolean highlightAMPMSelection) {
595 | this.highlightAMPMSelection = highlightAMPMSelection;
596 | }
597 |
598 | /**
599 | * Set timezone different from default
600 | */
601 | public void setTimeZone(TimeZone timeZone) {
602 | if (timeZone != null) {
603 | this.timeZone = timeZone;
604 | }
605 | }
606 |
607 | /**
608 | * Define if the AlertDialog must be styled, must be applied before "show"
609 | */
610 | public void setAlertStyle(@StyleRes int styleId) {
611 | this.alertStyleId = styleId;
612 | }
613 |
614 | /**
615 | * Class exception if SimpleDateFormat contains something else that "d" or/and "M"
616 | */
617 | public static class SimpleDateMonthAndDayFormatException extends Exception {
618 | SimpleDateMonthAndDayFormatException(String message) {
619 | super(message);
620 | }
621 | }
622 |
623 | /**
624 | * Callback class for assign action on positive and negative button
625 | */
626 | public interface OnButtonClickListener {
627 | void onPositiveButtonClick(Date date);
628 |
629 | void onNegativeButtonClick(Date date);
630 | }
631 |
632 | /**
633 | * Callback class for assign action on positive, negative and neutral button
634 | */
635 | public interface OnButtonWithNeutralClickListener extends OnButtonClickListener {
636 | void onNeutralButtonClick(Date date);
637 | }
638 |
639 | /**
640 | * Enumeration of header views
641 | */
642 | public enum HeaderViewsPosition {
643 | VIEW_HOURS_AND_MINUTES(0), VIEW_MONTH_AND_DAY(1), VIEW_YEAR(2);
644 |
645 | private final int positionSwitch;
646 |
647 | HeaderViewsPosition(int position) {
648 | this.positionSwitch = position;
649 | }
650 |
651 | public int getPosition() {
652 | return positionSwitch;
653 | }
654 | }
655 |
656 | /**
657 | * Listener for click on Header element
658 | */
659 | public class OnClickHeaderElementListener implements View.OnClickListener {
660 | private final int positionView;
661 |
662 | OnClickHeaderElementListener(int positionView) {
663 | this.positionView = positionView;
664 | }
665 |
666 | @Override
667 | public void onClick(View view) {
668 | Utils.animLabelElement(view);
669 | if (viewSwitcher.getDisplayedChild() != positionView)
670 | viewSwitcher.setDisplayedChild(positionView);
671 |
672 | startAtPosition = positionView;
673 | }
674 | }
675 | }
676 |
677 |
--------------------------------------------------------------------------------