├── .gitignore
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── vsnappy1
│ │ └── composecalendarexample
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── vsnappy1
│ │ │ └── composecalendarexample
│ │ │ ├── MainActivity.kt
│ │ │ └── ui
│ │ │ └── theme
│ │ │ ├── Color.kt
│ │ │ ├── Theme.kt
│ │ │ └── Type.kt
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── themes.xml
│ │ └── xml
│ │ ├── backup_rules.xml
│ │ └── data_extraction_rules.xml
│ └── test
│ └── java
│ └── com
│ └── vsnappy1
│ └── composecalendarexample
│ └── ExampleUnitTest.kt
├── build.gradle
├── composeDatePicker
├── .gitignore
├── build.gradle
├── consumer-rules.pro
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── vsnappy1
│ │ └── datepicker
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── vsnappy1
│ │ │ ├── component
│ │ │ └── Component.kt
│ │ │ ├── datepicker
│ │ │ ├── DatePicker.kt
│ │ │ ├── data
│ │ │ │ ├── Constant.kt
│ │ │ │ ├── DefaultDatePickerConfig.kt
│ │ │ │ └── model
│ │ │ │ │ ├── DatePickerDate.kt
│ │ │ │ │ ├── Month.kt
│ │ │ │ │ └── SelectionLimiter.kt
│ │ │ ├── enums
│ │ │ │ └── Days.kt
│ │ │ └── ui
│ │ │ │ ├── model
│ │ │ │ ├── DatePickerConfiguration.kt
│ │ │ │ └── DatePickerUiState.kt
│ │ │ │ └── viewmodel
│ │ │ │ └── DatePickerViewModel.kt
│ │ │ ├── extension
│ │ │ └── Extension.kt
│ │ │ ├── theme
│ │ │ ├── Color.kt
│ │ │ └── Size.kt
│ │ │ └── timepicker
│ │ │ ├── TimePicker.kt
│ │ │ ├── data
│ │ │ ├── Constant.kt
│ │ │ ├── DefaultTimePickerConfig.kt
│ │ │ └── model
│ │ │ │ └── TimePickerTime.kt
│ │ │ ├── enums
│ │ │ ├── MinuteGap.kt
│ │ │ └── TimeOfDay.kt
│ │ │ └── ui
│ │ │ ├── model
│ │ │ ├── TimePickerConfiguration.kt
│ │ │ └── TimePickerUiState.kt
│ │ │ └── viewmodel
│ │ │ └── TimePickerViewModel.kt
│ └── res
│ │ └── values
│ │ └── strings.xml
│ └── test
│ └── java
│ └── com
│ └── vsnappy1
│ ├── MainCoroutineRule.kt
│ ├── datepicker
│ ├── ExampleUnitTest.kt
│ └── ui
│ │ └── viewmodel
│ │ └── DatePickerViewModelTest.kt
│ └── timepicker
│ └── ui
│ └── viewmodel
│ └── TimePickerViewModelTest.kt
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── jitpack.yml
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | .idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 | .cxx
10 | local.properties
11 |
--------------------------------------------------------------------------------
/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 [yyyy] [name of copyright owner]
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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ComposeDatePicker
2 | An Android Jetpack Compose library that provides a Composable Date Picker / Time Picker functionality.
3 |
4 | [](https://jitpack.io/#vsnappy1/ComposeDatePicker)
5 | [](https://android-arsenal.com/api?level=24)
6 |
7 |
8 |
9 |
10 |
11 | ## Setup
12 | __Step 1.__ Add the JitPack repository to your build file (Add it in your root *__build.gradle__* at the end of repositories)
13 | ```kotlin
14 | allprojects {
15 | repositories {
16 | ..
17 | maven { url 'https://jitpack.io' }
18 | }
19 | }
20 | ```
21 | __Note*__ In newer projects you can add it in *__settings.gradle__*
22 |
23 | __Step 2.__ Add the dependency
24 | ```kotlin
25 | dependencies {
26 | ..
27 | implementation 'com.github.vsnappy1:ComposeDatePicker:2.2.0'
28 | }
29 | ```
30 |
31 | ## Usage
32 | Adding a date picker or time picker is incredibly easy, requiring just two lines of code.
33 |
34 | ```kotlin
35 | DatePicker(onDateSelected = { year, month, day ->
36 |
37 | })
38 | ```
39 | 
40 | 
41 |
42 |
43 |
44 | ```kotlin
45 | TimePicker(onTimeSelected = { hour, minute ->
46 |
47 | })
48 | ```
49 | 
50 | 
51 |
52 |
53 | ## Customization
54 | The date and time picker offer extensive customization options, allowing users to modify the
55 | TextStyle, Color, Size, Shape, and other elements to align with their preferred theme.
56 |
57 | ### Date Picker
58 | ___
59 | #### Set Custom Date
60 | ```kotlin
61 | DatePicker(
62 | onDateSelected = { year, month, day ->
63 | },
64 | date = DatePickerDate(year = 2023, month = 0, day = 5)
65 | )
66 | ```
67 | Please note that the **_year_** should be within a range of ± 100 (inclusive). Additionally, for the **_month_**,
68 | please keep in mind that 0 represents January, while 11 corresponds to December.
69 |
70 | #### Set Selection Limit
71 | ```kotlin
72 | DatePicker(
73 | onDateSelected = { year, month, day ->
74 | },
75 | selectionLimiter = SelectionLimiter(
76 | fromDate = DatePickerDate(year = 2023, month = 4, day = 7),
77 | toDate = DatePickerDate(year = 2023, month = 4, day = 21)
78 | )
79 | )
80 | ```
81 |
82 | #### Customize the Appearance
83 | ```kotlin
84 | DatePicker(
85 | modifier = Modifier.padding(16.dp),
86 | onDateSelected = { year, month, day ->
87 | },
88 | configuration = DatePickerConfiguration.Builder()
89 | .height(height = 300.dp)
90 | .dateTextStyle(DefaultDatePickerConfig.dateTextStyle.copy(color = Color(0xFF333333)))
91 | .selectedDateTextStyle(textStyle = TextStyle(Color(0xFFFFFFFF)))
92 | .selectedDateBackgroundColor(color = Color(0xFF64DD17))
93 | .build()
94 | )
95 | ```
96 | In addition to **_dateTextStyle_**, **_selectedDateTextStyle_**, and **_selectedDateBackgroundColor_**, there are a total of
97 | 20 attributes available for users to customize the appearance of the date picker.
98 |
99 |
100 |
101 | ### Time Picker
102 | ___
103 | #### Set Custom Time
104 | ```kotlin
105 | TimePicker(
106 | onTimeSelected = { hour, minute ->
107 | },
108 | time = TimePickerTime(
109 | hour = 12,
110 | minute = 45
111 | )
112 | )
113 | ```
114 |
115 | #### Set Is24Hour & MinuteGap
116 | ```kotlin
117 | TimePicker(
118 | onTimeSelected = { hour, minute ->
119 | },
120 | is24Hour = true,
121 | minuteGap = MinuteGap.FIVE
122 | )
123 | ```
124 | The interval between consecutive items in the minute list is determined by the **_minuteGap_** parameter. When minuteGap is set to MinuteGap.FIVE, the minutes in the time picker will be displayed in increments of 5, such as 00, 05, 10,..., 55. The default value for minuteGap is MinuteGap.ONE, which means the minutes will be displayed in sequential order from 00 to 59.
125 |
126 |
127 | #### Customize the Appearance
128 | ```kotlin
129 | TimePicker(
130 | modifier = Modifier
131 | .padding(16.dp)
132 | .background(Color(0xFF1B5E20), RoundedCornerShape(8.dp)),
133 | onTimeSelected = { hour, minute ->
134 | },
135 | configuration = TimePickerConfiguration.Builder()
136 | .numberOfTimeRowsDisplayed(count = 5)
137 | .selectedTimeScaleFactor(scaleFactor = 1.4f)
138 | .build()
139 | )
140 | ```
141 | There are a total of 8 attributes available for users to customize the appearance of the time picker.
142 |
143 |
144 | ## Troubleshot
145 |
146 | * If multiple date/time pickers are used, a unique **_id_** parameter should be included in the function call for each composable.
147 |
148 | * When adjusting the height of a date/time picker, it is recommended to use **_TimePickerConfiguration.Builder().height()_** instead of **_Modifier.height()_** to ensure smooth rendering.
149 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'org.jetbrains.kotlin.android'
4 | }
5 |
6 | android {
7 | namespace 'com.vsnappy1.composecalendarexample'
8 | compileSdk 33
9 |
10 | defaultConfig {
11 | applicationId "com.vsnappy1.composecalendarexample"
12 | minSdk 24
13 | targetSdk 33
14 | versionCode 1
15 | versionName "1.0"
16 |
17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
18 | vectorDrawables {
19 | useSupportLibrary true
20 | }
21 | }
22 |
23 | buildTypes {
24 | release {
25 | minifyEnabled false
26 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
27 | }
28 | }
29 | compileOptions {
30 | sourceCompatibility JavaVersion.VERSION_1_8
31 | targetCompatibility JavaVersion.VERSION_1_8
32 | }
33 | kotlinOptions {
34 | jvmTarget = '1.8'
35 | }
36 | buildFeatures {
37 | compose true
38 | }
39 |
40 | composeOptions {
41 | kotlinCompilerExtensionVersion '1.4.7'
42 | }
43 | packagingOptions {
44 | resources {
45 | excludes += '/META-INF/{AL2.0,LGPL2.1}'
46 | }
47 | }
48 | }
49 |
50 | dependencies {
51 |
52 | implementation project(path: ':composeDatePicker')
53 | implementation 'androidx.core:core-ktx:1.10.1'
54 | implementation 'androidx.appcompat:appcompat:1.6.1'
55 | implementation 'com.google.android.material:material:1.9.0'
56 | testImplementation 'junit:junit:4.13.2'
57 | androidTestImplementation 'androidx.test.ext:junit:1.1.5'
58 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
59 |
60 | // Compose
61 | implementation platform('androidx.compose:compose-bom:2022.10.00')
62 | implementation 'androidx.compose.ui:ui'
63 | implementation 'androidx.compose.ui:ui-graphics'
64 | implementation 'androidx.compose.ui:ui-tooling-preview'
65 | implementation 'androidx.compose.material3:material3'
66 | implementation "androidx.compose.ui:ui-tooling"
67 | implementation "androidx.compose.runtime:runtime-livedata"
68 | implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.6.1'
69 | implementation 'androidx.activity:activity-compose:1.7.1'
70 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/vsnappy1/composecalendarexample/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.composecalendarexample
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.vsnappy1.composecalendarexample", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
15 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vsnappy1/composecalendarexample/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.composecalendarexample
2 |
3 | import android.os.Bundle
4 | import android.widget.Toast
5 | import androidx.activity.ComponentActivity
6 | import androidx.activity.compose.setContent
7 | import androidx.compose.foundation.layout.Column
8 | import androidx.compose.foundation.layout.fillMaxSize
9 | import androidx.compose.foundation.layout.padding
10 | import androidx.compose.material3.MaterialTheme
11 | import androidx.compose.material3.Surface
12 | import androidx.compose.material3.Text
13 | import androidx.compose.runtime.getValue
14 | import androidx.compose.runtime.mutableStateOf
15 | import androidx.compose.runtime.remember
16 | import androidx.compose.runtime.setValue
17 | import androidx.compose.ui.Modifier
18 | import androidx.compose.ui.unit.dp
19 | import com.vsnappy1.composecalendarexample.ui.theme.ComposeCalendarExampleTheme
20 | import com.vsnappy1.datepicker.DatePicker
21 | import com.vsnappy1.timepicker.TimePicker
22 | import com.vsnappy1.timepicker.data.model.TimePickerTime
23 | import com.vsnappy1.timepicker.enums.MinuteGap
24 |
25 | class MainActivity : ComponentActivity() {
26 | override fun onCreate(savedInstanceState: Bundle?) {
27 | super.onCreate(savedInstanceState)
28 | setContent {
29 | ComposeCalendarExampleTheme {
30 | // A surface container using the 'background' color from the theme
31 | Surface(
32 | modifier = Modifier.fillMaxSize(),
33 | color = MaterialTheme.colorScheme.background
34 | ) {
35 | Column {
36 | DatePicker(
37 | modifier = Modifier.padding(16.dp),
38 | onDateSelected = { year, month, day ->
39 | Toast.makeText(this@MainActivity, "$year/$month/$day", Toast.LENGTH_SHORT)
40 | .show()
41 | }
42 | )
43 | var text by remember{ mutableStateOf("") }
44 | TimePicker(
45 | onTimeSelected = { hour, minute ->
46 | text = "$hour : $minute "
47 | },
48 | time = TimePickerTime(5, 5),
49 | minuteGap = MinuteGap.FIVE
50 | )
51 | Text(text)
52 | }
53 | }
54 | }
55 | }
56 | }
57 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/vsnappy1/composecalendarexample/ui/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.composecalendarexample.ui.theme
2 |
3 | import androidx.compose.ui.graphics.Color
4 |
5 | val Purple80 = Color(0xFFD0BCFF)
6 | val PurpleGrey80 = Color(0xFFCCC2DC)
7 | val Pink80 = Color(0xFFEFB8C8)
8 |
9 | val Purple40 = Color(0xFF6650a4)
10 | val PurpleGrey40 = Color(0xFF625b71)
11 | val Pink40 = Color(0xFF7D5260)
--------------------------------------------------------------------------------
/app/src/main/java/com/vsnappy1/composecalendarexample/ui/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.composecalendarexample.ui.theme
2 |
3 | import android.app.Activity
4 | import android.os.Build
5 | import androidx.compose.foundation.isSystemInDarkTheme
6 | import androidx.compose.material3.MaterialTheme
7 | import androidx.compose.material3.darkColorScheme
8 | import androidx.compose.material3.dynamicDarkColorScheme
9 | import androidx.compose.material3.dynamicLightColorScheme
10 | import androidx.compose.material3.lightColorScheme
11 | import androidx.compose.runtime.Composable
12 | import androidx.compose.runtime.SideEffect
13 | import androidx.compose.ui.graphics.toArgb
14 | import androidx.compose.ui.platform.LocalContext
15 | import androidx.compose.ui.platform.LocalView
16 | import androidx.core.view.WindowCompat
17 |
18 | private val DarkColorScheme = darkColorScheme(
19 | primary = Purple80,
20 | secondary = PurpleGrey80,
21 | tertiary = Pink80
22 | )
23 |
24 | private val LightColorScheme = lightColorScheme(
25 | primary = Purple40,
26 | secondary = PurpleGrey40,
27 | tertiary = Pink40
28 |
29 | /* Other default colors to override
30 | background = Color(0xFFFFFBFE),
31 | surface = Color(0xFFFFFBFE),
32 | onPrimary = Color.White,
33 | onSecondary = Color.White,
34 | onTertiary = Color.White,
35 | onBackground = Color(0xFF1C1B1F),
36 | onSurface = Color(0xFF1C1B1F),
37 | */
38 | )
39 |
40 | @Composable
41 | fun ComposeCalendarExampleTheme(
42 | darkTheme: Boolean = isSystemInDarkTheme(),
43 | // Dynamic color is available on Android 12+
44 | dynamicColor: Boolean = true,
45 | content: @Composable () -> Unit
46 | ) {
47 | val colorScheme = when {
48 | dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
49 | val context = LocalContext.current
50 | if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
51 | }
52 |
53 | darkTheme -> DarkColorScheme
54 | else -> LightColorScheme
55 | }
56 | val view = LocalView.current
57 | if (!view.isInEditMode) {
58 | SideEffect {
59 | val window = (view.context as Activity).window
60 | window.statusBarColor = colorScheme.primary.toArgb()
61 | WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
62 | }
63 | }
64 |
65 | MaterialTheme(
66 | colorScheme = colorScheme,
67 | typography = Typography,
68 | content = content
69 | )
70 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/vsnappy1/composecalendarexample/ui/theme/Type.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.composecalendarexample.ui.theme
2 |
3 | import androidx.compose.material3.Typography
4 | import androidx.compose.ui.text.TextStyle
5 | import androidx.compose.ui.text.font.FontFamily
6 | import androidx.compose.ui.text.font.FontWeight
7 | import androidx.compose.ui.unit.sp
8 |
9 | // Set of Material typography styles to start with
10 | val Typography = Typography(
11 | bodyLarge = TextStyle(
12 | fontFamily = FontFamily.Default,
13 | fontWeight = FontWeight.Normal,
14 | fontSize = 16.sp,
15 | lineHeight = 24.sp,
16 | letterSpacing = 0.5.sp
17 | )
18 | /* Other default text styles to override
19 | titleLarge = TextStyle(
20 | fontFamily = FontFamily.Default,
21 | fontWeight = FontWeight.Normal,
22 | fontSize = 22.sp,
23 | lineHeight = 28.sp,
24 | letterSpacing = 0.sp
25 | ),
26 | labelSmall = TextStyle(
27 | fontFamily = FontFamily.Default,
28 | fontWeight = FontWeight.Medium,
29 | fontSize = 11.sp,
30 | lineHeight = 16.sp,
31 | letterSpacing = 0.5.sp
32 | )
33 | */
34 | )
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vsnappy1/ComposeDatePicker/570dc841875f439ef6152820dba0466ae117683c/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vsnappy1/ComposeDatePicker/570dc841875f439ef6152820dba0466ae117683c/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vsnappy1/ComposeDatePicker/570dc841875f439ef6152820dba0466ae117683c/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vsnappy1/ComposeDatePicker/570dc841875f439ef6152820dba0466ae117683c/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vsnappy1/ComposeDatePicker/570dc841875f439ef6152820dba0466ae117683c/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vsnappy1/ComposeDatePicker/570dc841875f439ef6152820dba0466ae117683c/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vsnappy1/ComposeDatePicker/570dc841875f439ef6152820dba0466ae117683c/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vsnappy1/ComposeDatePicker/570dc841875f439ef6152820dba0466ae117683c/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vsnappy1/ComposeDatePicker/570dc841875f439ef6152820dba0466ae117683c/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vsnappy1/ComposeDatePicker/570dc841875f439ef6152820dba0466ae117683c/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | ComposeCalendarExample
3 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/app/src/test/java/com/vsnappy1/composecalendarexample/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.composecalendarexample
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 | plugins {
3 | id 'com.android.application' version '8.0.1' apply false
4 | id 'com.android.library' version '8.0.1' apply false
5 | id 'org.jetbrains.kotlin.android' version '1.8.21' apply false
6 | }
7 |
8 |
--------------------------------------------------------------------------------
/composeDatePicker/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/composeDatePicker/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'org.jetbrains.kotlin.android'
4 | id 'maven-publish'
5 | }
6 |
7 | android {
8 | namespace 'com.vsnappy1.composedatepicker'
9 | compileSdk 33
10 | buildToolsVersion '33.0.0'
11 |
12 | defaultConfig {
13 | minSdk 24
14 | targetSdk 33
15 | versionCode 1
16 | versionName "1.0"
17 |
18 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
19 | consumerProguardFiles "consumer-rules.pro"
20 | }
21 |
22 | buildTypes {
23 | release {
24 | minifyEnabled false
25 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
26 | }
27 | }
28 | compileOptions {
29 | sourceCompatibility JavaVersion.VERSION_1_8
30 | targetCompatibility JavaVersion.VERSION_1_8
31 | }
32 | kotlinOptions {
33 | jvmTarget = '1.8'
34 | }
35 | composeOptions {
36 | kotlinCompilerExtensionVersion '1.4.7'
37 | }
38 | buildFeatures {
39 | compose true
40 | }
41 | }
42 |
43 | dependencies {
44 |
45 | implementation 'androidx.core:core-ktx:1.10.1'
46 | implementation 'androidx.appcompat:appcompat:1.6.1'
47 | implementation 'com.google.android.material:material:1.9.0'
48 | testImplementation 'junit:junit:4.13.2'
49 | androidTestImplementation 'androidx.test.ext:junit:1.1.5'
50 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
51 |
52 | // Compose
53 | implementation platform('androidx.compose:compose-bom:2022.10.00')
54 | implementation 'androidx.compose.ui:ui'
55 | implementation 'androidx.compose.ui:ui-graphics'
56 | implementation 'androidx.compose.ui:ui-tooling-preview'
57 | implementation 'androidx.compose.material3:material3'
58 | implementation "androidx.compose.ui:ui-tooling"
59 | implementation "androidx.compose.runtime:runtime-livedata"
60 | implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.6.1'
61 | implementation 'androidx.activity:activity-compose:1.7.1'
62 |
63 | //Testing
64 | testImplementation "androidx.arch.core:core-testing:2.2.0"
65 | testImplementation 'org.mockito:mockito-core:4.4.0'
66 | testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4'
67 | }
68 |
69 | afterEvaluate {
70 | publishing {
71 | publications {
72 | // Creates a Maven publication called "release".
73 | maven(MavenPublication) {
74 | // Applies the component for the release build variant.
75 | from components.release
76 |
77 | // You can then customize attributes of the publication as shown below.
78 | groupId = "com.github.vsnappy1"
79 | artifactId = "composedatepicker"
80 | version = "1.0"
81 | }
82 | }
83 | repositories {
84 | mavenLocal()
85 | mavenCentral()
86 | }
87 | }
88 | }
89 |
90 |
91 |
--------------------------------------------------------------------------------
/composeDatePicker/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vsnappy1/ComposeDatePicker/570dc841875f439ef6152820dba0466ae117683c/composeDatePicker/consumer-rules.pro
--------------------------------------------------------------------------------
/composeDatePicker/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/composeDatePicker/src/androidTest/java/com/vsnappy1/datepicker/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.datepicker
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.vsnappy1.composecalendar.test", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/component/Component.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.component
2 |
3 | import android.annotation.SuppressLint
4 | import androidx.compose.animation.AnimatedVisibility
5 | import androidx.compose.animation.AnimatedVisibilityScope
6 | import androidx.compose.animation.core.tween
7 | import androidx.compose.animation.fadeIn
8 | import androidx.compose.animation.fadeOut
9 | import androidx.compose.foundation.interaction.DragInteraction
10 | import androidx.compose.foundation.layout.height
11 | import androidx.compose.foundation.lazy.LazyColumn
12 | import androidx.compose.foundation.lazy.LazyListScope
13 | import androidx.compose.foundation.lazy.LazyListState
14 | import androidx.compose.runtime.Composable
15 | import androidx.compose.runtime.LaunchedEffect
16 | import androidx.compose.runtime.getValue
17 | import androidx.compose.runtime.mutableStateOf
18 | import androidx.compose.runtime.remember
19 | import androidx.compose.runtime.setValue
20 | import androidx.compose.ui.Modifier
21 | import androidx.compose.ui.unit.Dp
22 | import kotlinx.coroutines.delay
23 |
24 | @Composable
25 | fun AnimatedFadeVisibility(
26 | visible: Boolean,
27 | content: @Composable AnimatedVisibilityScope.() -> Unit
28 | ) {
29 | AnimatedVisibility(
30 | visible = visible,
31 | enter = fadeIn(animationSpec = tween(durationMillis = 400, delayMillis = 200)),
32 | exit = fadeOut(animationSpec = tween(durationMillis = 250, delayMillis = 100))
33 | ) {
34 | content()
35 | }
36 | }
37 |
38 | @SuppressLint("FrequentlyChangedStateReadInComposition")
39 | @Composable
40 | fun SwipeLazyColumn(
41 | modifier: Modifier = Modifier,
42 | selectedIndex: Int,
43 | onSelectedIndexChange: (Int) -> Unit,
44 | height: Dp,
45 | isAutoScrolling: Boolean,
46 | isScrollingToSelectedItemEnabled: Boolean = false,
47 | numberOfRowsDisplayed: Int,
48 | listState: LazyListState,
49 | onScrollingStopped: () -> Unit,
50 | content: LazyListScope.() -> Unit
51 | ) {
52 | var isManualScrolling by remember { mutableStateOf(true) }
53 | var isInitialWaitOver by remember { mutableStateOf(false) }
54 |
55 | LaunchedEffect(key1 = Unit) {
56 | delay(250)
57 | isInitialWaitOver =
58 | true // because not two animateScrollToItem should be called at once and this delay protect that from happening.
59 | }
60 |
61 | if (isScrollingToSelectedItemEnabled) {
62 | LaunchedEffect(key1 = selectedIndex) {
63 | if (isInitialWaitOver) {
64 | isManualScrolling = false
65 | if (!listState.isScrollInProgress) {
66 | listState.animateScrollToItem(selectedIndex)
67 | }
68 | delay(10)
69 | isManualScrolling = true
70 | }
71 | }
72 | }
73 |
74 | // Update selected item index
75 | LaunchedEffect(key1 = listState.firstVisibleItemScrollOffset) {
76 | if (!isAutoScrolling && isManualScrolling && isInitialWaitOver) {
77 | val index =
78 | listState.firstVisibleItemIndex + if (listState.firstVisibleItemScrollOffset > height.value / numberOfRowsDisplayed) 1 else 0
79 | onSelectedIndexChange(index)
80 | }
81 | }
82 |
83 | // For smooth scrolling to center item
84 | var isAnimateScrollToItemTriggered by remember { mutableStateOf(false) }
85 | LaunchedEffect(key1 = listState.isScrollInProgress) {
86 | if (!isAnimateScrollToItemTriggered) {
87 | listState.animateScrollToItem(selectedIndex)
88 | isAnimateScrollToItemTriggered = true
89 | onScrollingStopped()
90 | }
91 | }
92 | LaunchedEffect(key1 = listState.interactionSource.interactions) {
93 | listState.interactionSource.interactions.collect {
94 | if (it is DragInteraction.Start) {
95 | isAnimateScrollToItemTriggered = false
96 | }
97 | }
98 | }
99 |
100 | LazyColumn(
101 | modifier = modifier
102 | .height(height),
103 | state = listState
104 | ) {
105 | content()
106 | }
107 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/datepicker/DatePicker.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.datepicker
2 |
3 | import androidx.compose.animation.animateColorAsState
4 | import androidx.compose.animation.core.animateFloatAsState
5 | import androidx.compose.animation.core.tween
6 | import androidx.compose.foundation.background
7 | import androidx.compose.foundation.layout.Arrangement
8 | import androidx.compose.foundation.layout.Box
9 | import androidx.compose.foundation.layout.Row
10 | import androidx.compose.foundation.layout.Spacer
11 | import androidx.compose.foundation.layout.fillMaxSize
12 | import androidx.compose.foundation.layout.fillMaxWidth
13 | import androidx.compose.foundation.layout.height
14 | import androidx.compose.foundation.layout.padding
15 | import androidx.compose.foundation.layout.size
16 | import androidx.compose.foundation.layout.width
17 | import androidx.compose.foundation.lazy.grid.GridCells
18 | import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
19 | import androidx.compose.foundation.lazy.grid.items
20 | import androidx.compose.foundation.lazy.rememberLazyListState
21 | import androidx.compose.material.icons.Icons
22 | import androidx.compose.material.icons.rounded.KeyboardArrowLeft
23 | import androidx.compose.material.icons.rounded.KeyboardArrowRight
24 | import androidx.compose.material3.Icon
25 | import androidx.compose.material3.Text
26 | import androidx.compose.runtime.Composable
27 | import androidx.compose.runtime.LaunchedEffect
28 | import androidx.compose.runtime.getValue
29 | import androidx.compose.runtime.livedata.observeAsState
30 | import androidx.compose.runtime.mutableStateOf
31 | import androidx.compose.runtime.remember
32 | import androidx.compose.runtime.rememberCoroutineScope
33 | import androidx.compose.runtime.setValue
34 | import androidx.compose.ui.Alignment
35 | import androidx.compose.ui.Modifier
36 | import androidx.compose.ui.draw.clip
37 | import androidx.compose.ui.draw.scale
38 | import androidx.compose.ui.graphics.Color
39 | import androidx.compose.ui.layout.onGloballyPositioned
40 | import androidx.compose.ui.platform.LocalDensity
41 | import androidx.compose.ui.res.stringResource
42 | import androidx.compose.ui.text.style.TextAlign
43 | import androidx.compose.ui.tooling.preview.Preview
44 | import androidx.compose.ui.unit.Dp
45 | import androidx.compose.ui.unit.dp
46 | import androidx.lifecycle.viewmodel.compose.viewModel
47 | import com.vsnappy1.component.AnimatedFadeVisibility
48 | import com.vsnappy1.composedatepicker.R
49 | import com.vsnappy1.datepicker.ui.model.DatePickerConfiguration
50 | import com.vsnappy1.datepicker.data.Constant
51 | import com.vsnappy1.datepicker.data.model.DatePickerDate
52 | import com.vsnappy1.datepicker.data.model.DefaultDate
53 | import com.vsnappy1.datepicker.data.model.Month
54 | import com.vsnappy1.datepicker.data.model.SelectionLimiter
55 | import com.vsnappy1.datepicker.enums.Days
56 | import com.vsnappy1.datepicker.ui.model.DatePickerUiState
57 | import com.vsnappy1.datepicker.ui.viewmodel.DatePickerViewModel
58 | import com.vsnappy1.extension.noRippleClickable
59 | import com.vsnappy1.extension.spToDp
60 | import com.vsnappy1.extension.toDp
61 | import com.vsnappy1.theme.Size.medium
62 | import kotlinx.coroutines.launch
63 | import kotlin.math.ceil
64 |
65 |
66 | @Composable
67 | fun DatePicker(
68 | modifier: Modifier = Modifier,
69 | onDateSelected: (Int, Int, Int) -> Unit,
70 | date: DatePickerDate = DefaultDate.defaultDate,
71 | selectionLimiter: SelectionLimiter = SelectionLimiter(),
72 | configuration: DatePickerConfiguration = DatePickerConfiguration.Builder().build(),
73 | id: Int = 1
74 | ) {
75 | val viewModel: DatePickerViewModel = viewModel(key = "DatePickerViewModel$id")
76 | val uiState by viewModel.uiState.observeAsState(
77 | DatePickerUiState(
78 | selectedYear = date.year,
79 | selectedMonth = Constant.getMonths(date.year)[date.month],
80 | selectedDayOfMonth = date.day
81 | )
82 | )
83 | // Key is Unit because I want this to run only once not every time when is composable is recomposed.
84 | LaunchedEffect(key1 = Unit) { viewModel.setDate(date) }
85 |
86 | var height by remember { mutableStateOf(configuration.height) }
87 | Box(modifier = modifier.onGloballyPositioned {
88 | if (it.size.height == 0) return@onGloballyPositioned
89 | height = it.size.height.toDp() - configuration.headerHeight// Update the height
90 | }) {
91 | // TODO add sliding effect when next or previous arrow is pressed
92 | CalendarHeader(
93 | title = "${uiState.currentVisibleMonth.name} ${uiState.selectedYear}",
94 | onMonthYearClick = { viewModel.toggleIsMonthYearViewVisible() },
95 | onNextClick = { viewModel.moveToNextMonth() },
96 | onPreviousClick = { viewModel.moveToPreviousMonth() },
97 | isPreviousNextVisible = !uiState.isMonthYearViewVisible,
98 | themeColor = configuration.selectedDateBackgroundColor,
99 | configuration = configuration,
100 | )
101 | Box(
102 | modifier = Modifier
103 | .padding(top = configuration.headerHeight)
104 | .height(height)
105 | ) {
106 | AnimatedFadeVisibility(
107 | visible = !uiState.isMonthYearViewVisible
108 | ) {
109 | DateView(
110 | currentVisibleMonth = uiState.currentVisibleMonth,
111 | selectedYear = uiState.selectedYear,
112 | selectedMonth = uiState.selectedMonth,
113 | selectedDayOfMonth = uiState.selectedDayOfMonth,
114 | selectionLimiter = selectionLimiter,
115 | height = height,
116 | onDaySelected = {
117 | viewModel.updateSelectedDayAndMonth(it)
118 | onDateSelected(
119 | uiState.selectedYear,
120 | uiState.selectedMonth.number,
121 | uiState.selectedDayOfMonth
122 | )
123 | },
124 | configuration = configuration
125 | )
126 | }
127 | AnimatedFadeVisibility(
128 | visible = uiState.isMonthYearViewVisible
129 | ) {
130 | MonthAndYearView(
131 | modifier = Modifier.align(Alignment.Center),
132 | selectedMonth = uiState.selectedMonthIndex,
133 | onMonthChange = { viewModel.updateSelectedMonthIndex(it) },
134 | selectedYear = uiState.selectedYearIndex,
135 | onYearChange = { viewModel.updateSelectedYearIndex(it) },
136 | years = uiState.years,
137 | months = uiState.months,
138 | height = height,
139 | configuration = configuration
140 | )
141 | }
142 | }
143 | }
144 | // Call onDateSelected when composition is completed
145 | LaunchedEffect(key1 = Unit) {
146 | onDateSelected(
147 | uiState.selectedYear,
148 | uiState.selectedMonth.number,
149 | uiState.selectedDayOfMonth
150 | )
151 | }
152 | }
153 |
154 | @Composable
155 | private fun MonthAndYearView(
156 | modifier: Modifier = Modifier,
157 | selectedMonth: Int,
158 | onMonthChange: (Int) -> Unit,
159 | selectedYear: Int,
160 | onYearChange: (Int) -> Unit,
161 | years: List,
162 | months: List,
163 | height: Dp,
164 | configuration: DatePickerConfiguration
165 | ) {
166 | Box(
167 | contentAlignment = Alignment.Center,
168 | modifier = modifier
169 | .fillMaxSize(),
170 | ) {
171 | Box(
172 | modifier = modifier
173 | .padding(horizontal = medium)
174 | .fillMaxWidth()
175 | .height(configuration.selectedMonthYearAreaHeight)
176 | .background(
177 | color = configuration.selectedMonthYearAreaColor,
178 | shape = configuration.selectedMonthYearAreaShape
179 | )
180 | )
181 | Row(
182 | modifier = Modifier.fillMaxSize(),
183 | horizontalArrangement = Arrangement.Center,
184 | verticalAlignment = Alignment.CenterVertically
185 | ) {
186 | SwipeLazyColumn(
187 | modifier = Modifier.weight(0.5f),
188 | selectedIndex = selectedMonth,
189 | onSelectedIndexChange = onMonthChange,
190 | items = months,
191 | height = height,
192 | configuration = configuration
193 | )
194 | SwipeLazyColumn(
195 | modifier = Modifier.weight(0.5f),
196 | selectedIndex = selectedYear,
197 | onSelectedIndexChange = onYearChange,
198 | items = years,
199 | alignment = Alignment.CenterEnd,
200 | height = height,
201 | configuration = configuration
202 | )
203 | }
204 | }
205 | }
206 |
207 | @Composable
208 | private fun SwipeLazyColumn(
209 | modifier: Modifier = Modifier,
210 | selectedIndex: Int,
211 | onSelectedIndexChange: (Int) -> Unit,
212 | items: List,
213 | alignment: Alignment = Alignment.CenterStart,
214 | configuration: DatePickerConfiguration,
215 | height: Dp
216 | ) {
217 | val coroutineScope = rememberCoroutineScope()
218 | var isAutoScrolling by remember { mutableStateOf(false) }
219 | val listState = rememberLazyListState(selectedIndex)
220 | com.vsnappy1.component.SwipeLazyColumn(
221 | modifier = modifier,
222 | selectedIndex = selectedIndex,
223 | onSelectedIndexChange = onSelectedIndexChange,
224 | isAutoScrolling = isAutoScrolling,
225 | height = height,
226 | numberOfRowsDisplayed = configuration.numberOfMonthYearRowsDisplayed,
227 | listState = listState,
228 | onScrollingStopped = {}
229 | ) {
230 | // I add some empty rows at the beginning and end of list to make it feel that it is a center focused list
231 | val count = items.size + configuration.numberOfMonthYearRowsDisplayed - 1
232 | items(count) {
233 | SliderItem(
234 | value = it,
235 | selectedIndex = selectedIndex,
236 | items = items,
237 | configuration = configuration,
238 | alignment = alignment,
239 | height = height,
240 | onItemClick = { index ->
241 | onSelectedIndexChange(index)
242 | coroutineScope.launch {
243 | isAutoScrolling = true
244 | onSelectedIndexChange(index)
245 | listState.animateScrollToItem(index)
246 | isAutoScrolling = false
247 | }
248 | }
249 | )
250 | }
251 | }
252 | }
253 |
254 | @Composable
255 | private fun SliderItem(
256 | value: Int,
257 | selectedIndex: Int,
258 | items: List,
259 | onItemClick: (Int) -> Unit,
260 | alignment: Alignment,
261 | configuration: DatePickerConfiguration,
262 | height: Dp
263 | ) {
264 | // this gap variable helps in maintaining list as center focused list
265 | val gap = configuration.numberOfMonthYearRowsDisplayed / 2
266 | val isSelected = value == selectedIndex + gap
267 | val scale by animateFloatAsState(targetValue = if (isSelected) configuration.selectedMonthYearScaleFactor else 1f)
268 | Box(
269 | modifier = Modifier
270 | .height(height / (configuration.numberOfMonthYearRowsDisplayed))
271 | ) {
272 | if (value >= gap && value < items.size + gap) {
273 | Box(
274 | modifier = Modifier
275 | .fillMaxSize()
276 | .noRippleClickable {
277 | onItemClick(value - gap)
278 | },
279 | contentAlignment = if (alignment == Alignment.CenterEnd) Alignment.CenterStart else Alignment.CenterEnd
280 | ) {
281 | configuration.selectedMonthYearTextStyle.fontSize
282 | Box(
283 | modifier = Modifier.width(
284 | configuration.selectedMonthYearTextStyle.fontSize.spToDp(LocalDensity.current) * 5
285 | )
286 | ) {
287 | Text(
288 | text = items[value - gap],
289 | modifier = Modifier
290 | .align(alignment)
291 | .scale(scale),
292 | style = if (isSelected) configuration.selectedMonthYearTextStyle
293 | else configuration.monthYearTextStyle
294 | )
295 | }
296 | }
297 | }
298 | }
299 | }
300 |
301 | @Composable
302 | private fun DateView(
303 | modifier: Modifier = Modifier,
304 | selectedYear: Int,
305 | currentVisibleMonth: Month,
306 | selectedDayOfMonth: Int?,
307 | selectionLimiter: SelectionLimiter,
308 | onDaySelected: (Int) -> Unit,
309 | selectedMonth: Month,
310 | height: Dp,
311 | configuration: DatePickerConfiguration
312 | ) {
313 | LazyVerticalGrid(
314 | columns = GridCells.Fixed(7),
315 | userScrollEnabled = false,
316 | modifier = modifier
317 | ) {
318 | items(Constant.days) {
319 | DateViewHeaderItem(day = it, configuration = configuration)
320 | }
321 | // since I may need few empty cells because every month starts with a different day(Monday, Tuesday, ..)
322 | // that's way I add some number X into the count
323 | val count =
324 | currentVisibleMonth.numberOfDays + currentVisibleMonth.firstDayOfMonth.number - 1
325 | val topPaddingForItem =
326 | getTopPaddingForItem(
327 | count,
328 | height - configuration.selectedDateBackgroundSize * 2, // because I don't want to count first two rows
329 | configuration.selectedDateBackgroundSize
330 | )
331 | items(count) {
332 | if (it < currentVisibleMonth.firstDayOfMonth.number - 1) return@items // to create empty boxes
333 | DateViewBodyItem(
334 | value = it,
335 | currentVisibleMonth = currentVisibleMonth,
336 | selectedYear = selectedYear,
337 | selectedMonth = selectedMonth,
338 | selectedDayOfMonth = selectedDayOfMonth,
339 | selectionLimiter = selectionLimiter,
340 | onDaySelected = onDaySelected,
341 | topPaddingForItem = topPaddingForItem,
342 | configuration = configuration,
343 | )
344 | }
345 | }
346 | }
347 |
348 | @Composable
349 | private fun DateViewBodyItem(
350 | value: Int,
351 | currentVisibleMonth: Month,
352 | selectedYear: Int,
353 | selectedMonth: Month,
354 | selectedDayOfMonth: Int?,
355 | selectionLimiter: SelectionLimiter,
356 | onDaySelected: (Int) -> Unit,
357 | topPaddingForItem: Dp,
358 | configuration: DatePickerConfiguration,
359 | ) {
360 | Box(
361 | contentAlignment = Alignment.Center
362 | ) {
363 | val day = value - currentVisibleMonth.firstDayOfMonth.number + 2
364 | val isSelected = day == selectedDayOfMonth && selectedMonth == currentVisibleMonth
365 | val isWithinRange = selectionLimiter.isWithinRange(
366 | DatePickerDate(
367 | selectedYear,
368 | currentVisibleMonth.number,
369 | day
370 | )
371 | )
372 | Box(
373 | contentAlignment = Alignment.Center, modifier = Modifier
374 | .padding(top = if (value < 7) 0.dp else topPaddingForItem) // I don't want first row to have any padding
375 | .size(configuration.selectedDateBackgroundSize)
376 | .clip(configuration.selectedDateBackgroundShape)
377 | .noRippleClickable(enabled = isWithinRange) { onDaySelected(day) }
378 | .background(if (isSelected) configuration.selectedDateBackgroundColor else Color.Transparent)
379 | ) {
380 | Text(
381 | text = "$day",
382 | textAlign = TextAlign.Center,
383 | style = if (isSelected) configuration.selectedDateTextStyle
384 | .copy(color = if (isWithinRange) configuration.selectedDateTextStyle.color else configuration.disabledDateColor)
385 | else configuration.dateTextStyle.copy(
386 | color = if (isWithinRange) {
387 | if (value % 7 == 0) configuration.sundayTextColor
388 | else configuration.dateTextStyle.color
389 | } else {
390 | configuration.disabledDateColor
391 | }
392 | ),
393 | )
394 | }
395 | }
396 | }
397 |
398 | @Composable
399 | private fun DateViewHeaderItem(
400 | configuration: DatePickerConfiguration,
401 | day: Days
402 | ) {
403 | Box(
404 | contentAlignment = Alignment.Center, modifier = Modifier
405 | .size(configuration.selectedDateBackgroundSize)
406 | ) {
407 | Text(
408 | text = day.abbreviation,
409 | textAlign = TextAlign.Center,
410 | style = configuration.daysNameTextStyle.copy(
411 | color = if (day.number == 1) configuration.sundayTextColor else configuration.daysNameTextStyle.color
412 | ),
413 | )
414 | }
415 | }
416 |
417 | // Not every month has same number of weeks, so to maintain the same size for calender I add padding if there are less weeks
418 | private fun getTopPaddingForItem(
419 | count: Int,
420 | height: Dp,
421 | size: Dp
422 | ): Dp {
423 | val numberOfRowsVisible = ceil(count.toDouble() / 7) - 1
424 | val result =
425 | (height - (size * numberOfRowsVisible.toInt()) - medium) / numberOfRowsVisible.toInt()
426 | return if (result > 0.dp) result else 0.dp
427 | }
428 |
429 | @Composable
430 | private fun CalendarHeader(
431 | modifier: Modifier = Modifier,
432 | title: String,
433 | onNextClick: () -> Unit,
434 | onPreviousClick: () -> Unit,
435 | onMonthYearClick: () -> Unit,
436 | isPreviousNextVisible: Boolean,
437 | configuration: DatePickerConfiguration,
438 | themeColor: Color
439 | ) {
440 | Box(
441 | modifier = Modifier
442 | .fillMaxWidth()
443 | .height(configuration.headerHeight)
444 | ) {
445 | val textColor by
446 | animateColorAsState(
447 | targetValue = if (isPreviousNextVisible) configuration.headerTextStyle.color else themeColor,
448 | animationSpec = tween(durationMillis = 400, delayMillis = 100)
449 | )
450 | Text(
451 | text = title,
452 | style = configuration.headerTextStyle.copy(color = textColor),
453 | modifier = modifier
454 | .padding(start = medium)
455 | .noRippleClickable { onMonthYearClick() }
456 | .align(Alignment.CenterStart),
457 | )
458 |
459 | Row(modifier = Modifier.align(Alignment.CenterEnd)) {
460 | AnimatedFadeVisibility(visible = isPreviousNextVisible) {
461 | Icon(
462 | imageVector = Icons.Rounded.KeyboardArrowLeft,
463 | contentDescription = stringResource(id = R.string.leftArrow),
464 | tint = configuration.headerArrowColor,
465 | modifier = Modifier
466 | .size(configuration.headerArrowSize)
467 | .noRippleClickable { onPreviousClick() }
468 | )
469 | }
470 | Spacer(modifier = Modifier.width(medium))
471 | AnimatedFadeVisibility(visible = isPreviousNextVisible) {
472 | Icon(
473 | imageVector = Icons.Rounded.KeyboardArrowRight,
474 | contentDescription = stringResource(id = R.string.leftArrow),
475 | tint = configuration.headerArrowColor,
476 | modifier = Modifier
477 | .size(configuration.headerArrowSize)
478 | .noRippleClickable { onNextClick() }
479 | )
480 | }
481 | }
482 | }
483 | }
484 |
485 |
486 | @Preview
487 | @Composable
488 | fun DefaultDatePicker() {
489 | DatePicker(onDateSelected = { _: Int, _: Int, _: Int -> })
490 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/datepicker/data/Constant.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.datepicker.data
2 |
3 | import com.vsnappy1.datepicker.enums.Days
4 | import com.vsnappy1.datepicker.enums.Days.FRIDAY
5 | import com.vsnappy1.datepicker.enums.Days.MONDAY
6 | import com.vsnappy1.datepicker.enums.Days.SATURDAY
7 | import com.vsnappy1.datepicker.enums.Days.SUNDAY
8 | import com.vsnappy1.datepicker.enums.Days.THURSDAY
9 | import com.vsnappy1.datepicker.enums.Days.TUESDAY
10 | import com.vsnappy1.datepicker.enums.Days.WEDNESDAY
11 | import com.vsnappy1.datepicker.data.model.Month
12 | import com.vsnappy1.extension.isLeapYear
13 | import java.util.Calendar
14 |
15 | internal object Constant {
16 | private const val repeatCount: Int = 200
17 |
18 | val days = listOf(
19 | SUNDAY,
20 | MONDAY,
21 | TUESDAY,
22 | WEDNESDAY,
23 | THURSDAY,
24 | FRIDAY,
25 | SATURDAY
26 | )
27 |
28 | private val monthNames = listOf(
29 | "January",
30 | "February",
31 | "March",
32 | "April",
33 | "May",
34 | "June",
35 | "July",
36 | "August",
37 | "September",
38 | "October",
39 | "November",
40 | "December",
41 | )
42 |
43 | fun getMonths(): List {
44 | val list = mutableListOf()
45 | for (i in 1..repeatCount) {
46 | list.addAll(monthNames)
47 | }
48 | return list
49 | }
50 |
51 | fun getMiddleOfMonth(): Int {
52 | return 12 * (repeatCount / 2)
53 | }
54 |
55 | fun getMonths(year: Int): List {
56 | return listOf(
57 | Month("January", 31, getFirstDayOfMonth(0, year), 0),
58 | Month("February", if (year.isLeapYear()) 29 else 28, getFirstDayOfMonth(1, year), 1),
59 | Month("March", 31, getFirstDayOfMonth(2, year), 2),
60 | Month("April", 30, getFirstDayOfMonth(3, year), 3),
61 | Month("May", 31, getFirstDayOfMonth(4, year), 4),
62 | Month("June", 30, getFirstDayOfMonth(5, year), 5),
63 | Month("July", 31, getFirstDayOfMonth(6, year), 6),
64 | Month("August", 31, getFirstDayOfMonth(7, year), 7),
65 | Month("September", 30, getFirstDayOfMonth(8, year), 8),
66 | Month("October", 31, getFirstDayOfMonth(9, year), 9),
67 | Month("November", 30, getFirstDayOfMonth(10, year), 10),
68 | Month("December", 31, getFirstDayOfMonth(11, year), 11)
69 | )
70 | }
71 |
72 | private fun getFirstDayOfMonth(month: Int, year: Int): Days {
73 | val calendar = Calendar.getInstance()
74 | calendar.set(year, month, 1)
75 | return Days.get(calendar[Calendar.DAY_OF_WEEK])
76 | }
77 |
78 | val years = List(200) { it + Calendar.getInstance()[Calendar.YEAR] - 100 }
79 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/datepicker/data/DefaultDatePickerConfig.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.datepicker.data
2 |
3 | import androidx.compose.foundation.shape.CircleShape
4 | import androidx.compose.foundation.shape.RoundedCornerShape
5 | import androidx.compose.ui.graphics.Color
6 | import androidx.compose.ui.graphics.Shape
7 | import androidx.compose.ui.text.TextStyle
8 | import androidx.compose.ui.text.font.FontWeight
9 | import androidx.compose.ui.unit.Dp
10 | import androidx.compose.ui.unit.dp
11 | import androidx.compose.ui.unit.sp
12 | import com.vsnappy1.theme.Size
13 | import com.vsnappy1.theme.black
14 | import com.vsnappy1.theme.blue
15 | import com.vsnappy1.theme.grayDark
16 | import com.vsnappy1.theme.grayLight
17 | import com.vsnappy1.theme.red
18 | import com.vsnappy1.theme.white
19 |
20 | class DefaultDatePickerConfig private constructor() {
21 |
22 | companion object {
23 | val height: Dp = 260.dp
24 |
25 | // Header configuration
26 | val headerHeight: Dp = 35.dp
27 | val headerTextStyle: TextStyle = TextStyle(
28 | fontSize = 16.sp,
29 | fontWeight = FontWeight.W700,
30 | color = black
31 | )
32 | val headerArrowSize: Dp = 35.dp
33 | val headerArrowColor: Color = black
34 |
35 | // Date view configuration
36 | val daysNameTextStyle: TextStyle = TextStyle(
37 | fontSize = 12.sp,
38 | fontWeight = FontWeight.W500,
39 | color = grayDark
40 | )
41 | val dateTextStyle: TextStyle = TextStyle(
42 | fontSize = 16.sp,
43 | fontWeight = FontWeight.W500,
44 | color = black
45 | )
46 | val selectedDateTextStyle: TextStyle = TextStyle(
47 | fontSize = 16.sp,
48 | fontWeight = FontWeight.W600,
49 | color = white
50 | )
51 | val sundayTextColor: Color = red
52 | val disabledDateColor: Color = grayLight
53 | val selectedDateBackgroundSize: Dp = 35.dp
54 | val selectedDateBackgroundColor: Color = blue
55 | val selectedDateBackgroundShape: Shape = CircleShape
56 |
57 | // Month Year view configuration
58 | val monthYearTextStyle: TextStyle = TextStyle(
59 | fontSize = 16.sp,
60 | fontWeight = FontWeight.W500,
61 | color = black.copy(alpha = 0.5f)
62 | )
63 | val selectedMonthYearTextStyle: TextStyle = TextStyle(
64 | fontSize = 17.sp,
65 | fontWeight = FontWeight.W600,
66 | color = black.copy(alpha = 1f)
67 | )
68 | const val numberOfMonthYearRowsDisplayed: Int = 7
69 | const val selectedMonthYearScaleFactor: Float = 1.2f
70 | val selectedMonthYearAreaHeight: Dp = 35.dp
71 | val selectedMonthYearAreaColor: Color = grayLight.copy(alpha = 0.2f)
72 | val selectedMonthYearAreaShape: Shape = RoundedCornerShape(Size.medium)
73 | }
74 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/datepicker/data/model/DatePickerDate.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.datepicker.data.model
2 |
3 | import android.icu.util.Calendar
4 |
5 | data class DatePickerDate(
6 | val year: Int,
7 | val month: Int,
8 | val day: Int
9 | )
10 |
11 | object DefaultDate {
12 | private val calendar = Calendar.getInstance()
13 | val defaultDate = DatePickerDate(
14 | calendar[Calendar.YEAR],
15 | calendar[Calendar.MONTH],
16 | calendar[Calendar.DAY_OF_MONTH]
17 | )
18 | }
19 |
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/datepicker/data/model/Month.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.datepicker.data.model
2 |
3 | import com.vsnappy1.datepicker.enums.Days
4 |
5 | data class Month(
6 | val name: String,
7 | val numberOfDays: Int,
8 | val firstDayOfMonth: Days,
9 | val number: Int
10 | )
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/datepicker/data/model/SelectionLimiter.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.datepicker.data.model
2 |
3 | import com.vsnappy1.extension.isEqual
4 | import java.util.Calendar
5 |
6 | class SelectionLimiter(
7 | private val fromDate: DatePickerDate? = null,
8 | private val toDate: DatePickerDate? = null
9 | ) {
10 | fun isWithinRange(date: DatePickerDate): Boolean {
11 |
12 |
13 | val fromDate =
14 | fromDate?.let {
15 | Calendar.getInstance().apply {
16 | set(it.year, it.month, it.day, 0, 0)
17 | }
18 | }
19 | val toDate =
20 | toDate?.let {
21 | Calendar.getInstance().apply {
22 | set(it.year, it.month, it.day, 0, 0)
23 | }
24 | }
25 |
26 | val selectedDate = Calendar.getInstance().apply {
27 | set(date.year, date.month, date.day, 0, 0)
28 | }
29 |
30 | return when {
31 | fromDate == null && toDate == null -> {
32 | return true
33 | }
34 |
35 | fromDate != null && toDate != null -> {
36 | (selectedDate.before(toDate) && selectedDate.after(fromDate)) ||
37 | (selectedDate.isEqual(toDate) || selectedDate.isEqual(fromDate))
38 | }
39 |
40 | fromDate != null -> {
41 | selectedDate.after(fromDate) || selectedDate.isEqual(fromDate)
42 | }
43 |
44 | toDate != null -> {
45 | selectedDate.before(toDate) || selectedDate.isEqual(toDate)
46 | }
47 |
48 | else -> {
49 | true
50 | }
51 | }
52 | }
53 | }
54 |
55 |
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/datepicker/enums/Days.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.datepicker.enums
2 |
3 | enum class Days(val abbreviation: String, val value: String, val number: Int) {
4 | SUNDAY("SUN", "Sunday", 1),
5 | MONDAY("MON", "Monday", 2),
6 | TUESDAY("TUE", "Tuesday", 3),
7 | WEDNESDAY("WED", "Wednesday", 4),
8 | THURSDAY("THU", "Thursday", 5),
9 | FRIDAY("FRI", "Friday", 6),
10 | SATURDAY("SAT", "Saturday", 7);
11 |
12 | companion object {
13 | fun get(number: Int): Days {
14 | return when (number) {
15 | 1 -> SUNDAY
16 | 2 -> MONDAY
17 | 3 -> TUESDAY
18 | 4 -> WEDNESDAY
19 | 5 -> THURSDAY
20 | 6 -> FRIDAY
21 | else -> SATURDAY
22 | }
23 | }
24 | }
25 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/datepicker/ui/model/DatePickerConfiguration.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.datepicker.ui.model
2 |
3 | import androidx.compose.ui.graphics.Color
4 | import androidx.compose.ui.graphics.Shape
5 | import androidx.compose.ui.text.TextStyle
6 | import androidx.compose.ui.unit.Dp
7 | import com.vsnappy1.datepicker.data.DefaultDatePickerConfig
8 |
9 | class DatePickerConfiguration private constructor(
10 | val height: Dp,
11 | val headerHeight: Dp,
12 | val headerTextStyle: TextStyle,
13 | val headerArrowSize: Dp,
14 | val headerArrowColor: Color,
15 | val daysNameTextStyle: TextStyle,
16 | val dateTextStyle: TextStyle,
17 | val selectedDateTextStyle: TextStyle,
18 | val sundayTextColor: Color,
19 | val disabledDateColor: Color,
20 | val selectedDateBackgroundSize: Dp,
21 | val selectedDateBackgroundColor: Color,
22 | val selectedDateBackgroundShape: Shape,
23 | val monthYearTextStyle: TextStyle,
24 | val selectedMonthYearTextStyle: TextStyle,
25 | val selectedMonthYearScaleFactor: Float,
26 | val numberOfMonthYearRowsDisplayed: Int,
27 | val selectedMonthYearAreaHeight: Dp,
28 | val selectedMonthYearAreaColor: Color,
29 | val selectedMonthYearAreaShape: Shape
30 | ) {
31 | class Builder {
32 | private var height: Dp = DefaultDatePickerConfig.height
33 | private var headerHeight: Dp = DefaultDatePickerConfig.headerHeight
34 | private var headerTextStyle: TextStyle = DefaultDatePickerConfig.headerTextStyle
35 | private var headerArrowSize: Dp = DefaultDatePickerConfig.headerArrowSize
36 | private var headerArrowColor: Color = DefaultDatePickerConfig.headerArrowColor
37 | private var daysNameTextStyle: TextStyle = DefaultDatePickerConfig.daysNameTextStyle
38 | private var dateTextStyle: TextStyle = DefaultDatePickerConfig.dateTextStyle
39 | private var selectedDateTextStyle: TextStyle = DefaultDatePickerConfig.selectedDateTextStyle
40 | private var sundayTextColor: Color = DefaultDatePickerConfig.sundayTextColor
41 | private var disabledDateColor: Color = DefaultDatePickerConfig.disabledDateColor
42 | private var selectedDateBackgroundSize: Dp =
43 | DefaultDatePickerConfig.selectedDateBackgroundSize
44 | private var selectedDateBackgroundColor: Color =
45 | DefaultDatePickerConfig.selectedDateBackgroundColor
46 | private var selectedDateBackgroundShape: Shape =
47 | DefaultDatePickerConfig.selectedDateBackgroundShape
48 | private var monthYearTextStyle: TextStyle = DefaultDatePickerConfig.monthYearTextStyle
49 | private var selectedMonthYearTextStyle: TextStyle =
50 | DefaultDatePickerConfig.selectedMonthYearTextStyle
51 | private var numberOfMonthYearRowsDisplayed: Int =
52 | DefaultDatePickerConfig.numberOfMonthYearRowsDisplayed
53 | private var selectedMonthYearScaleFactor: Float =
54 | DefaultDatePickerConfig.selectedMonthYearScaleFactor
55 | private var selectedMonthYearAreaHeight: Dp =
56 | DefaultDatePickerConfig.selectedMonthYearAreaHeight
57 | private var selectedMonthYearAreaColor: Color =
58 | DefaultDatePickerConfig.selectedMonthYearAreaColor
59 | private var selectedMonthYearAreaShape: Shape =
60 | DefaultDatePickerConfig.selectedMonthYearAreaShape
61 |
62 | fun height(height: Dp) =
63 | apply { this.height = height }
64 |
65 | fun headerHeight(height: Dp) =
66 | apply { this.headerHeight = height }
67 |
68 | fun headerTextStyle(textStyle: TextStyle) =
69 | apply { this.headerTextStyle = textStyle }
70 |
71 | fun headerArrowSize(size: Dp) =
72 | apply { this.headerArrowSize = size }
73 |
74 | fun headerArrowColor(color: Color) =
75 | apply { this.headerArrowColor = color }
76 |
77 | fun daysNameTextStyle(textStyle: TextStyle) =
78 | apply { this.daysNameTextStyle = textStyle }
79 |
80 | fun dateTextStyle(textStyle: TextStyle) =
81 | apply { this.dateTextStyle = textStyle }
82 |
83 | fun selectedDateTextStyle(textStyle: TextStyle) =
84 | apply { this.selectedDateTextStyle = textStyle }
85 |
86 | fun sundayTextColor(color: Color) =
87 | apply { this.sundayTextColor = color }
88 |
89 | fun disabledDateColor(color: Color) =
90 | apply { this.disabledDateColor = color }
91 |
92 | fun selectedDateBackgroundSize(size: Dp) =
93 | apply { this.selectedDateBackgroundSize = size }
94 |
95 | fun selectedDateBackgroundColor(color: Color) =
96 | apply { this.selectedDateBackgroundColor = color }
97 |
98 | fun selectedDateBackgroundShape(shape: Shape) =
99 | apply { this.selectedDateBackgroundShape = shape }
100 |
101 | fun monthYearTextStyle(textStyle: TextStyle) =
102 | apply { this.monthYearTextStyle = textStyle }
103 |
104 | fun selectedMonthYearTextStyle(textStyle: TextStyle) =
105 | apply { this.selectedMonthYearTextStyle = textStyle }
106 |
107 | fun selectedMonthYearScaleFactor(scaleFactor: Float) =
108 | apply { this.selectedMonthYearScaleFactor = scaleFactor }
109 |
110 | fun numberOfMonthYearRowsDisplayed(count: Int) =
111 | apply { this.numberOfMonthYearRowsDisplayed = count }
112 |
113 | fun selectedMonthYearAreaHeight(height: Dp) =
114 | apply { this.selectedMonthYearAreaHeight = height }
115 |
116 | fun selectedMonthYearAreaColor(color: Color) =
117 | apply { this.selectedMonthYearAreaColor = color }
118 |
119 | fun selectedMonthYearAreaShape(shape: Shape) =
120 | apply { this.selectedMonthYearAreaShape = shape }
121 |
122 | fun build(): DatePickerConfiguration {
123 | return DatePickerConfiguration(
124 | height = height,
125 | headerHeight = headerHeight,
126 | headerTextStyle = headerTextStyle,
127 | headerArrowSize = headerArrowSize,
128 | headerArrowColor = headerArrowColor,
129 | daysNameTextStyle = daysNameTextStyle,
130 | dateTextStyle = dateTextStyle,
131 | selectedDateTextStyle = selectedDateTextStyle,
132 | sundayTextColor = sundayTextColor,
133 | disabledDateColor = disabledDateColor,
134 | selectedDateBackgroundSize = selectedDateBackgroundSize,
135 | selectedDateBackgroundColor = selectedDateBackgroundColor,
136 | selectedDateBackgroundShape = selectedDateBackgroundShape,
137 | monthYearTextStyle = monthYearTextStyle,
138 | selectedMonthYearTextStyle = selectedMonthYearTextStyle,
139 | selectedMonthYearScaleFactor = selectedMonthYearScaleFactor,
140 | numberOfMonthYearRowsDisplayed = numberOfMonthYearRowsDisplayed,
141 | selectedMonthYearAreaHeight = selectedMonthYearAreaHeight,
142 | selectedMonthYearAreaColor = selectedMonthYearAreaColor,
143 | selectedMonthYearAreaShape = selectedMonthYearAreaShape
144 | )
145 | }
146 | }
147 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/datepicker/ui/model/DatePickerUiState.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.datepicker.ui.model
2 |
3 | import com.vsnappy1.datepicker.data.Constant
4 | import com.vsnappy1.datepicker.data.model.Month
5 | import java.util.Calendar
6 | import kotlin.streams.toList
7 |
8 | internal data class DatePickerUiState(
9 | val selectedYear: Int = Calendar.getInstance()[Calendar.YEAR],
10 | val selectedYearIndex: Int = Constant.years.size / 2,
11 | val selectedMonth: Month = Constant.getMonths(selectedYear)[Calendar.getInstance()[Calendar.MONTH]],
12 | val selectedMonthIndex: Int = Constant.getMiddleOfMonth() + selectedMonth.number,
13 | val currentVisibleMonth: Month = selectedMonth,
14 | val selectedDayOfMonth: Int = Calendar.getInstance()[Calendar.DAY_OF_MONTH],
15 | val years: List = Constant.years.stream().map { "$it" }.toList(),
16 | val months: List = Constant.getMonths(),
17 | val isMonthYearViewVisible: Boolean = false
18 | )
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/datepicker/ui/viewmodel/DatePickerViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.datepicker.ui.viewmodel
2 |
3 | import android.icu.util.Calendar
4 | import androidx.lifecycle.LiveData
5 | import androidx.lifecycle.MutableLiveData
6 | import androidx.lifecycle.ViewModel
7 | import androidx.lifecycle.viewModelScope
8 | import com.vsnappy1.datepicker.data.Constant
9 | import com.vsnappy1.datepicker.data.model.DatePickerDate
10 | import com.vsnappy1.datepicker.data.model.Month
11 | import com.vsnappy1.datepicker.ui.model.DatePickerUiState
12 | import kotlinx.coroutines.delay
13 | import kotlinx.coroutines.launch
14 |
15 | internal class DatePickerViewModel : ViewModel() {
16 |
17 | private var _uiState: MutableLiveData = MutableLiveData(DatePickerUiState())
18 | val uiState: LiveData = _uiState
19 | private lateinit var availableMonths: List
20 |
21 |
22 | init {
23 | uiState.value?.let {
24 | availableMonths = Constant.getMonths(it.selectedYear)
25 | }
26 | }
27 |
28 | private fun updateCurrentVisibleMonth(month: Int) {
29 | _uiState.value?.apply {
30 | _uiState.value = this.copy(
31 | currentVisibleMonth = availableMonths[month],
32 | selectedMonthIndex = getAdjustedSelectedMonthIndex(month)
33 | )
34 | }
35 | }
36 |
37 | fun updateSelectedMonthIndex(index: Int) {
38 | _uiState.value?.apply {
39 | _uiState.value = this.copy(
40 | selectedMonthIndex = index,
41 | currentVisibleMonth = availableMonths[index % 12]
42 | )
43 | }
44 | }
45 |
46 | fun updateSelectedDayAndMonth(day: Int) {
47 | _uiState.value = _uiState.value?.let {
48 | _uiState.value?.copy(
49 | selectedDayOfMonth = day,
50 | selectedMonth = it.currentVisibleMonth
51 | )
52 | }
53 | }
54 |
55 | fun moveToNextMonth() {
56 | _uiState.value?.apply {
57 | if (currentVisibleMonth.number == 11) { // if it is December
58 | val nextYearIndex = selectedYearIndex + 1
59 | if (nextYearIndex == years.size) return
60 | val nextYear = years[nextYearIndex].toInt()
61 | availableMonths = Constant.getMonths(nextYear)
62 | _uiState.value = _uiState.value?.copy(
63 | selectedYear = nextYear,
64 | selectedYearIndex = nextYearIndex,
65 | selectedMonthIndex = getAdjustedSelectedMonthIndex(selectedMonthIndex + 1),
66 | currentVisibleMonth = availableMonths[0]
67 | )
68 | } else {
69 | _uiState.value = _uiState.value?.copy(
70 | currentVisibleMonth = availableMonths[currentVisibleMonth.number + 1],
71 | selectedMonthIndex = getAdjustedSelectedMonthIndex(selectedMonthIndex + 1),
72 | )
73 | }
74 | }
75 | }
76 |
77 | fun moveToPreviousMonth() {
78 | _uiState.value?.apply {
79 | if (currentVisibleMonth.number == 0) { // if it is January
80 | val previousYearIndex = selectedYearIndex - 1
81 | if (previousYearIndex == -1) return
82 | val previousYear = years[previousYearIndex].toInt()
83 | availableMonths = Constant.getMonths(previousYear)
84 | _uiState.value = _uiState.value?.copy(
85 | selectedYear = previousYear,
86 | selectedYearIndex = previousYearIndex,
87 | selectedMonthIndex = getAdjustedSelectedMonthIndex(selectedMonthIndex - 1),
88 | currentVisibleMonth = availableMonths[11]
89 | )
90 | } else {
91 | _uiState.value = _uiState.value?.copy(
92 | currentVisibleMonth = availableMonths[currentVisibleMonth.number - 1],
93 | selectedMonthIndex = getAdjustedSelectedMonthIndex(selectedMonthIndex - 1),
94 | )
95 | }
96 | }
97 | }
98 |
99 | private fun getAdjustedSelectedMonthIndex(index: Int) = Constant.getMiddleOfMonth() + index % 12
100 |
101 | fun updateSelectedYearIndex(index: Int) {
102 | availableMonths = Constant.getMonths(Constant.years[index])
103 | _uiState.value = _uiState.value?.copy(
104 | selectedYearIndex = index,
105 | selectedYear = Constant.years[index],
106 | currentVisibleMonth = availableMonths[_uiState.value?.currentVisibleMonth?.number ?: 0]
107 | )
108 | }
109 |
110 | fun toggleIsMonthYearViewVisible() {
111 | if (_uiState.value?.isMonthYearViewVisible == true) {
112 | viewModelScope.launch {
113 | delay(250)
114 | _uiState.value = _uiState.value?.let {
115 | it.copy(
116 | selectedMonthIndex = getAdjustedSelectedMonthIndex(it.selectedMonthIndex)
117 | )
118 | }
119 | }
120 | }
121 | _uiState.value = _uiState.value?.let {
122 | it.copy(
123 | isMonthYearViewVisible = !it.isMonthYearViewVisible,
124 | )
125 | }
126 | }
127 |
128 | fun updateUiState(uiState: DatePickerUiState) {
129 | _uiState.value = uiState
130 | }
131 |
132 | fun setDate(
133 | date: DatePickerDate,
134 | calendar: Calendar = Calendar.getInstance()
135 | ) {
136 | val yearMin = Constant.years.first()
137 | val yearMax = Constant.years.last()
138 |
139 | if (date.year < yearMin || date.year > yearMax) {
140 | throw IllegalArgumentException("Invalid year: ${date.year}, The year value must be between $yearMin (inclusive) to $yearMax (inclusive).")
141 | }
142 | if (date.month < 0 || date.month > 11) {
143 | throw IllegalArgumentException("Invalid month: ${date.month}, The month value must be between 0 (inclusive) to 11 (inclusive).")
144 | }
145 |
146 | calendar[Calendar.YEAR] = date.year
147 | calendar[Calendar.MONTH] = date.month
148 |
149 | val maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
150 | if (date.day < 1) {
151 | throw IllegalArgumentException("Invalid day: ${date.day}, The day value must be greater than zero.")
152 | }
153 | if (date.day > maxDays) {
154 | throw IllegalArgumentException("Invalid day: ${date.day}, The day value must be less than equal to $maxDays for given month (${Constant.getMonths()[date.month]}).")
155 | }
156 |
157 | val index = Constant.years.indexOf(date.year)
158 | updateSelectedYearIndex(index)
159 | updateCurrentVisibleMonth(date.month)
160 | updateSelectedDayAndMonth(date.day)
161 | }
162 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/extension/Extension.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.extension
2 |
3 | import android.content.res.Resources
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.foundation.interaction.MutableInteractionSource
6 | import androidx.compose.runtime.remember
7 | import androidx.compose.ui.Modifier
8 | import androidx.compose.ui.composed
9 | import androidx.compose.ui.unit.Density
10 | import androidx.compose.ui.unit.Dp
11 | import androidx.compose.ui.unit.TextUnit
12 | import androidx.compose.ui.unit.dp
13 | import java.util.Calendar
14 |
15 | fun Int.isLeapYear(): Boolean {
16 | // A year is a leap year if it is divisible by 4
17 | // but not divisible by 100, unless it is also divisible by 400
18 | return this % 4 == 0 && (this % 100 != 0 || this % 400 == 0)
19 | }
20 |
21 | fun Modifier.noRippleClickable(enabled: Boolean = true, onClick: () -> Unit): Modifier = composed {
22 | clickable(
23 | indication = null,
24 | interactionSource = remember { MutableInteractionSource() },
25 | enabled = enabled
26 | ) {
27 | onClick()
28 | }
29 | }
30 |
31 | fun Calendar.isEqual(calendar: Calendar?): Boolean {
32 | calendar?.let {
33 | return get(Calendar.YEAR) == it[Calendar.YEAR] &&
34 | get(Calendar.MONTH) == it[Calendar.MONTH] &&
35 | get(Calendar.DAY_OF_MONTH) == it[Calendar.DAY_OF_MONTH]
36 | }
37 | return false
38 | }
39 |
40 | fun Int.toDp(): Dp = (this / Resources.getSystem().displayMetrics.density).dp
41 |
42 | fun TextUnit.spToDp(density: Density): Dp{
43 | return with(density) {
44 | this@spToDp.toDp()
45 | }
46 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.theme
2 |
3 | import androidx.compose.ui.graphics.Color
4 |
5 | val black = Color(0xFF333333)
6 | val white = Color(0xFFFFFFFF)
7 | val grayDark = Color(0xFF797979)
8 | val red = Color(0xFFff0000)
9 | val blue = Color(0xFF2979ff)
10 | val grayLight = Color(0xFFaaaaaa)
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/theme/Size.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.theme
2 |
3 | import androidx.compose.ui.unit.dp
4 |
5 | object Size {
6 | val extraSmall = 2.dp
7 | val small = 4.dp
8 | val medium = 8.dp
9 | val large = 12.dp
10 | val extraLarge = 16.dp
11 | }
12 |
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/timepicker/TimePicker.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.timepicker
2 |
3 | import android.text.format.DateFormat
4 | import androidx.compose.animation.core.animateFloatAsState
5 | import androidx.compose.foundation.background
6 | import androidx.compose.foundation.layout.Arrangement
7 | import androidx.compose.foundation.layout.Box
8 | import androidx.compose.foundation.layout.Row
9 | import androidx.compose.foundation.layout.fillMaxSize
10 | import androidx.compose.foundation.layout.fillMaxWidth
11 | import androidx.compose.foundation.layout.height
12 | import androidx.compose.foundation.layout.padding
13 | import androidx.compose.foundation.lazy.rememberLazyListState
14 | import androidx.compose.material3.Text
15 | import androidx.compose.runtime.Composable
16 | import androidx.compose.runtime.LaunchedEffect
17 | import androidx.compose.runtime.getValue
18 | import androidx.compose.runtime.livedata.observeAsState
19 | import androidx.compose.runtime.mutableStateOf
20 | import androidx.compose.runtime.remember
21 | import androidx.compose.runtime.rememberCoroutineScope
22 | import androidx.compose.runtime.setValue
23 | import androidx.compose.ui.Alignment
24 | import androidx.compose.ui.Modifier
25 | import androidx.compose.ui.draw.scale
26 | import androidx.compose.ui.layout.onGloballyPositioned
27 | import androidx.compose.ui.platform.LocalContext
28 | import androidx.compose.ui.text.style.TextAlign
29 | import androidx.compose.ui.tooling.preview.Preview
30 | import androidx.compose.ui.unit.Dp
31 | import androidx.compose.ui.unit.dp
32 | import androidx.lifecycle.viewmodel.compose.viewModel
33 | import com.vsnappy1.extension.noRippleClickable
34 | import com.vsnappy1.extension.toDp
35 | import com.vsnappy1.theme.Size.extraLarge
36 | import com.vsnappy1.theme.Size.medium
37 | import com.vsnappy1.timepicker.data.model.TimePickerTime
38 | import com.vsnappy1.timepicker.enums.MinuteGap
39 | import com.vsnappy1.timepicker.ui.model.TimePickerConfiguration
40 | import com.vsnappy1.timepicker.ui.viewmodel.TimePickerViewModel
41 | import kotlinx.coroutines.launch
42 |
43 | @Composable
44 | fun TimePicker(
45 | modifier: Modifier = Modifier,
46 | onTimeSelected: (Int, Int) -> Unit,
47 | is24Hour: Boolean? = null,
48 | minuteGap: MinuteGap = MinuteGap.ONE,
49 | time: TimePickerTime? = null,
50 | configuration: TimePickerConfiguration = TimePickerConfiguration.Builder().build(),
51 | id: Int = 1
52 | ) {
53 | val viewModel: TimePickerViewModel = viewModel(key = "TimePickerViewModel$id")
54 | val timePickerTime = time ?: TimePickerTime.getTime()
55 | val is24: Boolean = is24Hour ?: DateFormat.is24HourFormat(LocalContext.current)
56 | val timePickerUiState = viewModel.getUiStateTimeProvided(timePickerTime, minuteGap, is24)
57 | val uiState by viewModel.uiState.observeAsState(timePickerUiState)
58 | LaunchedEffect(key1 = Unit) { viewModel.updateUiState(timePickerTime, minuteGap, is24) }
59 |
60 | TimePickerView(
61 | modifier = modifier,
62 | hours = uiState.hours,
63 | selectedHourIndex = uiState.selectedHourIndex,
64 | onSelectedHourIndexChange = {
65 | viewModel.updateSelectedHourIndex(it)
66 | },
67 | minutes = uiState.minutes,
68 | selectedMinuteIndex = uiState.selectedMinuteIndex,
69 | onSelectedMinuteIndexChange = {
70 | viewModel.updateSelectedMinuteIndex(it)
71 | },
72 | timesOfDay = uiState.timesOfDay,
73 | selectedTimeOfDayIndex = uiState.selectedTimeOfDayIndex,
74 | onSelectedTimeOfDayIndexChange = {
75 | viewModel.updateSelectedTimeOfDayIndex(it)
76 | },
77 | is24Hour = uiState.is24Hour,
78 | configuration = configuration,
79 | onScrollingStopped = {
80 | viewModel.getSelectedTime()?.apply {
81 | onTimeSelected(hour, minute)
82 | }
83 | }
84 | )
85 | }
86 |
87 | @Composable
88 | private fun TimePickerView(
89 | modifier: Modifier = Modifier,
90 | hours: List,
91 | selectedHourIndex: Int,
92 | onSelectedHourIndexChange: (Int) -> Unit,
93 | minutes: List,
94 | selectedMinuteIndex: Int,
95 | onSelectedMinuteIndexChange: (Int) -> Unit,
96 | timesOfDay: List,
97 | selectedTimeOfDayIndex: Int,
98 | onSelectedTimeOfDayIndexChange: (Int) -> Unit,
99 | is24Hour: Boolean,
100 | configuration: TimePickerConfiguration,
101 | onScrollingStopped: () -> Unit,
102 | ) {
103 | var height by remember { mutableStateOf(configuration.height) }
104 | Box(
105 | contentAlignment = Alignment.Center,
106 | modifier = modifier
107 | .onGloballyPositioned {
108 | if (it.size.height == 0) return@onGloballyPositioned
109 | height = it.size.height.toDp() // Update the height
110 | },
111 | ) {
112 | Box(modifier = Modifier.fillMaxWidth())
113 | Box(
114 | modifier = Modifier
115 | .padding(horizontal = medium)
116 | .fillMaxWidth()
117 | .height(configuration.selectedTimeAreaHeight)
118 | .background(
119 | color = configuration.selectedTimeAreaColor,
120 | shape = configuration.selectedTimeAreaShape
121 | )
122 | )
123 | Row(
124 | horizontalArrangement = Arrangement.Center,
125 | verticalAlignment = Alignment.CenterVertically
126 | ) {
127 | SwipeLazyColumn(
128 | modifier = Modifier.weight(if (is24Hour) 0.5f else 0.4f),
129 | selectedIndex = selectedHourIndex,
130 | onSelectedIndexChange = onSelectedHourIndexChange,
131 | items = hours,
132 | alignment = Alignment.CenterEnd,
133 | configuration = configuration,
134 | height = height,
135 | onScrollingStopped = onScrollingStopped
136 | )
137 | SwipeLazyColumn(
138 | modifier = Modifier.weight(if (is24Hour) 0.5f else 0.2f),
139 | selectedIndex = selectedMinuteIndex,
140 | onSelectedIndexChange = onSelectedMinuteIndexChange,
141 | items = minutes,
142 | textAlign = if (is24Hour) TextAlign.Start else TextAlign.Center,
143 | alignment = if (is24Hour) Alignment.CenterStart else Alignment.Center,
144 | configuration = configuration,
145 | height = height,
146 | onScrollingStopped = onScrollingStopped
147 | )
148 | if (!is24Hour) {
149 | SwipeLazyColumn(
150 | modifier = Modifier.weight(0.4f),
151 | selectedIndex = selectedTimeOfDayIndex,
152 | onSelectedIndexChange = onSelectedTimeOfDayIndexChange,
153 | items = timesOfDay,
154 | alignment = Alignment.CenterStart,
155 | configuration = configuration,
156 | height = height,
157 | isScrollingToSelectedItemEnabled = true,
158 | onScrollingStopped = onScrollingStopped
159 | )
160 | }
161 | }
162 | }
163 | }
164 |
165 | @Composable
166 | private fun SwipeLazyColumn(
167 | modifier: Modifier = Modifier,
168 | selectedIndex: Int,
169 | onSelectedIndexChange: (Int) -> Unit,
170 | items: List,
171 | textAlign: TextAlign = TextAlign.End,
172 | alignment: Alignment = Alignment.CenterStart,
173 | configuration: TimePickerConfiguration,
174 | isScrollingToSelectedItemEnabled: Boolean = false,
175 | height: Dp,
176 | onScrollingStopped: () -> Unit
177 | ) {
178 | val coroutineScope = rememberCoroutineScope()
179 | var isAutoScrolling by remember { mutableStateOf(false) }
180 | val listState = rememberLazyListState(selectedIndex)
181 | com.vsnappy1.component.SwipeLazyColumn(
182 | modifier = modifier,
183 | selectedIndex = selectedIndex,
184 | onSelectedIndexChange = onSelectedIndexChange,
185 | isAutoScrolling = isAutoScrolling,
186 | height = height,
187 | isScrollingToSelectedItemEnabled = isScrollingToSelectedItemEnabled,
188 | numberOfRowsDisplayed = configuration.numberOfTimeRowsDisplayed,
189 | listState = listState,
190 | onScrollingStopped = {
191 | isAutoScrolling = false
192 | onScrollingStopped()
193 | }
194 | ) {
195 | // we add some empty rows at the beginning and end of list to make it feel that it is a center focused list
196 | val count = items.size + configuration.numberOfTimeRowsDisplayed - 1
197 | items(count) {
198 | SliderItem(
199 | value = it,
200 | selectedIndex = selectedIndex,
201 | items = items,
202 | configuration = configuration,
203 | alignment = alignment,
204 | textAlign = textAlign,
205 | height = height,
206 | onItemClick = { index ->
207 | coroutineScope.launch {
208 | isAutoScrolling = true
209 | onSelectedIndexChange(index)
210 | listState.animateScrollToItem(index)
211 | isAutoScrolling = false
212 | onScrollingStopped()
213 | }
214 | }
215 | )
216 | }
217 | }
218 | }
219 |
220 | @Composable
221 | private fun SliderItem(
222 | value: Int,
223 | selectedIndex: Int,
224 | items: List,
225 | onItemClick: (Int) -> Unit,
226 | alignment: Alignment,
227 | configuration: TimePickerConfiguration,
228 | height: Dp,
229 | textAlign: TextAlign,
230 | ) {
231 | // this gap variable helps in maintaining list as center focused list
232 | val gap = configuration.numberOfTimeRowsDisplayed / 2
233 | val isSelected = value == selectedIndex + gap
234 | val scale by animateFloatAsState(targetValue = if (isSelected) configuration.selectedTimeScaleFactor else 1f)
235 | Box(
236 | modifier = Modifier
237 | .height(height / configuration.numberOfTimeRowsDisplayed)
238 | .padding(
239 | start = if (alignment == Alignment.CenterStart) extraLarge else 0.dp,
240 | end = if (alignment == Alignment.CenterEnd) extraLarge else 0.dp
241 | )
242 | ) {
243 | if (value >= gap && value < items.size + gap) {
244 | Box(modifier = Modifier
245 | .fillMaxSize()
246 | .noRippleClickable {
247 | onItemClick(value - gap)
248 | }) {
249 | Text(
250 | text = items[value - gap],
251 | modifier = Modifier
252 | .align(alignment)
253 | .scale(scale),
254 | style = if (isSelected) configuration.selectedTimeTextStyle else configuration.timeTextStyle,
255 | textAlign = textAlign
256 | )
257 | }
258 | }
259 | }
260 | }
261 |
262 | @Preview
263 | @Composable
264 | fun PreviewTimePicker() {
265 | TimePicker(onTimeSelected = { _: Int, _: Int -> })
266 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/timepicker/data/Constant.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.timepicker.data
2 |
3 | import com.vsnappy1.timepicker.enums.MinuteGap
4 |
5 | internal object Constant {
6 |
7 | private const val repeatCount: Int = 200
8 |
9 | private fun findHours(is24Hour: Boolean): List {
10 | if (is24Hour) return listOf(
11 | "0",
12 | "1",
13 | "2",
14 | "3",
15 | "4",
16 | "5",
17 | "6",
18 | "7",
19 | "8",
20 | "9",
21 | "10",
22 | "11",
23 | "12",
24 | "13",
25 | "14",
26 | "15",
27 | "16",
28 | "17",
29 | "18",
30 | "19",
31 | "20",
32 | "21",
33 | "22",
34 | "23"
35 | )
36 | return listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12")
37 | }
38 |
39 | fun getHours(is24Hour: Boolean): List {
40 | val list = mutableListOf()
41 | for (i in 1..repeatCount) {
42 | list.addAll(findHours(is24Hour))
43 | }
44 | return list
45 | }
46 |
47 | fun getMiddleOfHour(is24Hour: Boolean): Int {
48 | return if (is24Hour) 24 * (repeatCount / 2)
49 | else 12 * (repeatCount / 2) - 1
50 | }
51 |
52 | private fun findMinutes(minuteGap: MinuteGap): List {
53 | var value = 0
54 | val list = mutableListOf()
55 | while (value < 60) {
56 | list.add("${if (value < 10) "0" else ""}${value}")
57 | value += minuteGap.gap
58 | }
59 | return list
60 | }
61 |
62 | fun getMinutes(minuteGap: MinuteGap): List {
63 | val list = mutableListOf()
64 | for (i in 1..repeatCount) {
65 | list.addAll(findMinutes(minuteGap))
66 | }
67 | return list
68 | }
69 |
70 | fun getMiddleOfMinute(minuteGap: MinuteGap): Int {
71 | return if (minuteGap.gap == 1) 60 * (repeatCount / 2)
72 | else if (minuteGap == MinuteGap.FIVE) 12 * (repeatCount / 2)
73 | else 6 * (repeatCount / 2)
74 | }
75 |
76 | fun getNearestNextMinute(minute: Int, minuteGap: MinuteGap): Int {
77 | if (minuteGap.gap == 1) return minute
78 | var value = 0
79 | while (value < minute) {
80 | value += minuteGap.gap
81 | }
82 | return if (value >= 60) 0
83 | else value
84 | }
85 |
86 | fun getTimesOfDay(): List {
87 | return listOf("AM", "PM")
88 | }
89 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/timepicker/data/DefaultTimePickerConfig.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.timepicker.data
2 |
3 | import androidx.compose.foundation.shape.RoundedCornerShape
4 | import androidx.compose.ui.graphics.Color
5 | import androidx.compose.ui.graphics.Shape
6 | import androidx.compose.ui.text.TextStyle
7 | import androidx.compose.ui.text.font.FontWeight
8 | import androidx.compose.ui.unit.Dp
9 | import androidx.compose.ui.unit.dp
10 | import androidx.compose.ui.unit.sp
11 | import com.vsnappy1.theme.Size
12 | import com.vsnappy1.theme.grayLight
13 |
14 | class DefaultTimePickerConfig private constructor() {
15 |
16 | companion object {
17 | val height: Dp = 200.dp
18 | val timeTextStyle: TextStyle = TextStyle(
19 | fontSize = 16.sp,
20 | fontWeight = FontWeight.W500,
21 | color = Color.Black.copy(alpha = 0.5f)
22 | )
23 | val selectedTimeTextStyle: TextStyle = TextStyle(
24 | fontSize = 17.sp,
25 | fontWeight = FontWeight.W600,
26 | color = Color.Black
27 | )
28 | const val numberOfTimeRowsDisplayed: Int = 7
29 | const val selectedTimeScaleFactor: Float = 1.2f
30 | val selectedTimeAreaHeight: Dp = 35.dp
31 | val selectedTimeAreaColor: Color = grayLight.copy(alpha = 0.2f)
32 | val selectedTimeAreaShape: Shape = RoundedCornerShape(Size.medium)
33 | }
34 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/timepicker/data/model/TimePickerTime.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.timepicker.data.model
2 |
3 | import java.util.Calendar
4 |
5 | class TimePickerTime(val hour: Int, val minute: Int) {
6 |
7 | companion object DefaultTime {
8 | fun getTime(): TimePickerTime {
9 | return TimePickerTime(
10 | Calendar.getInstance()[Calendar.HOUR_OF_DAY],
11 | Calendar.getInstance()[Calendar.MINUTE]
12 | )
13 | }
14 | }
15 | }
16 |
17 |
18 |
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/timepicker/enums/MinuteGap.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.timepicker.enums
2 |
3 | enum class MinuteGap(val gap: Int) {
4 | ONE(1),
5 | FIVE(5),
6 | TEN(10)
7 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/timepicker/enums/TimeOfDay.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.timepicker.enums
2 |
3 | enum class TimeOfDay(val value: Int) {
4 | AM(0), PM(1)
5 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/timepicker/ui/model/TimePickerConfiguration.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.timepicker.ui.model
2 |
3 | import androidx.compose.foundation.shape.RoundedCornerShape
4 | import androidx.compose.ui.graphics.Color
5 | import androidx.compose.ui.graphics.Shape
6 | import androidx.compose.ui.text.TextStyle
7 | import androidx.compose.ui.text.font.FontWeight
8 | import androidx.compose.ui.unit.Dp
9 | import androidx.compose.ui.unit.dp
10 | import androidx.compose.ui.unit.sp
11 | import com.vsnappy1.theme.Size
12 | import com.vsnappy1.theme.grayLight
13 | import com.vsnappy1.timepicker.data.DefaultTimePickerConfig
14 |
15 | class TimePickerConfiguration private constructor(
16 | val height: Dp,
17 | val timeTextStyle: TextStyle,
18 | val selectedTimeTextStyle: TextStyle,
19 | val numberOfTimeRowsDisplayed: Int,
20 | val selectedTimeScaleFactor: Float,
21 | val selectedTimeAreaHeight: Dp,
22 | val selectedTimeAreaColor: Color,
23 | val selectedTimeAreaShape: Shape
24 | ) {
25 | class Builder {
26 | private var height: Dp = DefaultTimePickerConfig.height
27 | private var timeTextStyle: TextStyle = DefaultTimePickerConfig.timeTextStyle
28 | private var selectedTimeTextStyle: TextStyle = DefaultTimePickerConfig.selectedTimeTextStyle
29 | private var numberOfTimeRowsDisplayed: Int =
30 | DefaultTimePickerConfig.numberOfTimeRowsDisplayed
31 | private var selectedTimeScaleFactor: Float = DefaultTimePickerConfig.selectedTimeScaleFactor
32 | private var selectedTimeAreaHeight: Dp = DefaultTimePickerConfig.selectedTimeAreaHeight
33 | private var selectedTimeAreaColor: Color = DefaultTimePickerConfig.selectedTimeAreaColor
34 | private var selectedTimeAreaShape: Shape = DefaultTimePickerConfig.selectedTimeAreaShape
35 |
36 | fun height(height: Dp) =
37 | apply { this.height = height }
38 |
39 | fun timeTextStyle(textStyle: TextStyle) =
40 | apply { this.timeTextStyle = textStyle }
41 |
42 | fun selectedTimeTextStyle(textStyle: TextStyle) =
43 | apply { this.selectedTimeTextStyle = textStyle }
44 |
45 | fun selectedTimeScaleFactor(scaleFactor: Float) =
46 | apply { this.selectedTimeScaleFactor = scaleFactor }
47 |
48 | fun numberOfTimeRowsDisplayed(count: Int) =
49 | apply { this.numberOfTimeRowsDisplayed = count }
50 |
51 | fun selectedTimeAreaHeight(height: Dp) =
52 | apply { this.selectedTimeAreaHeight = height }
53 |
54 | fun selectedTimeAreaColor(color: Color) =
55 | apply { this.selectedTimeAreaColor = color }
56 |
57 | fun selectedTimeAreaShape(shape: Shape) =
58 | apply { this.selectedTimeAreaShape = shape }
59 |
60 | fun build(): TimePickerConfiguration {
61 | return TimePickerConfiguration(
62 | height = height,
63 | timeTextStyle = timeTextStyle,
64 | selectedTimeTextStyle = selectedTimeTextStyle,
65 | numberOfTimeRowsDisplayed = numberOfTimeRowsDisplayed,
66 | selectedTimeScaleFactor = selectedTimeScaleFactor,
67 | selectedTimeAreaHeight = selectedTimeAreaHeight,
68 | selectedTimeAreaColor = selectedTimeAreaColor,
69 | selectedTimeAreaShape = selectedTimeAreaShape,
70 | )
71 | }
72 | }
73 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/timepicker/ui/model/TimePickerUiState.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.timepicker.ui.model
2 |
3 | import com.vsnappy1.timepicker.data.Constant
4 | import com.vsnappy1.timepicker.enums.MinuteGap
5 | import java.util.Calendar
6 |
7 | internal data class TimePickerUiState(
8 | val is24Hour: Boolean = false,
9 | val minuteGap: MinuteGap = MinuteGap.FIVE,
10 | val hours: List = Constant.getHours(is24Hour),
11 | val selectedHourIndex: Int = Constant.getMiddleOfHour(is24Hour) + Calendar.getInstance()[Calendar.HOUR_OF_DAY] + if (Constant.getNearestNextMinute(
12 | Calendar.getInstance()[Calendar.MINUTE],
13 | minuteGap
14 | ) == 0 && Calendar.getInstance()[Calendar.MINUTE] != 0
15 | ) 1 else 0,
16 | val minutes: List = Constant.getMinutes(minuteGap),
17 | val selectedMinuteIndex: Int = Constant.getMiddleOfMinute(minuteGap) + Constant.getNearestNextMinute(
18 | Calendar.getInstance()[Calendar.MINUTE], minuteGap
19 | ) / minuteGap.gap,
20 | val timesOfDay: List = Constant.getTimesOfDay(),
21 | val selectedTimeOfDayIndex: Int = if ((hours[selectedHourIndex].toInt() + if (is24Hour) 0 else (12 * Calendar.getInstance()[Calendar.AM_PM])) in 12..23) 1 else 0,
22 | )
23 |
--------------------------------------------------------------------------------
/composeDatePicker/src/main/java/com/vsnappy1/timepicker/ui/viewmodel/TimePickerViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.timepicker.ui.viewmodel
2 |
3 | import androidx.lifecycle.LiveData
4 | import androidx.lifecycle.MutableLiveData
5 | import androidx.lifecycle.ViewModel
6 | import androidx.lifecycle.viewModelScope
7 | import com.vsnappy1.timepicker.data.Constant
8 | import com.vsnappy1.timepicker.data.model.TimePickerTime
9 | import com.vsnappy1.timepicker.enums.MinuteGap
10 | import com.vsnappy1.timepicker.ui.model.TimePickerUiState
11 | import kotlinx.coroutines.delay
12 | import kotlinx.coroutines.launch
13 |
14 | internal class TimePickerViewModel : ViewModel() {
15 |
16 | private val _uiState: MutableLiveData = MutableLiveData(TimePickerUiState())
17 | val uiState: LiveData = _uiState
18 | private var hour: Int =
19 | 0 // When time of the day is manually selected by user we either add or subtract this
20 |
21 | fun updateSelectedHourIndex(index: Int) {
22 | _uiState.value = _uiState.value?.copy(selectedHourIndex = index)
23 | _uiState.value?.apply {
24 | if (!is24Hour) {
25 | viewModelScope.launch {
26 | delay(200)
27 | _uiState.value = _uiState.value?.copy(
28 | selectedTimeOfDayIndex = if ((index + 1 + hour) % 24 >= 12) 1 else 0
29 | )
30 | }
31 | }
32 | }
33 | }
34 |
35 | fun updateSelectedMinuteIndex(index: Int) {
36 | _uiState.value = _uiState.value?.copy(selectedMinuteIndex = index)
37 | }
38 |
39 | fun updateSelectedTimeOfDayIndex(index: Int) {
40 | if (index != _uiState.value?.selectedTimeOfDayIndex) {
41 | _uiState.value = _uiState.value?.copy(selectedTimeOfDayIndex = index)
42 | hour += if (index == 1) 12 else -12
43 | }
44 | }
45 |
46 | fun getSelectedTime(): TimePickerTime? {
47 | val time = _uiState.value?.let {
48 | var hour = it.hours[it.selectedHourIndex].toInt()
49 | if (!it.is24Hour) {
50 | hour = hour % 12 + if (it.selectedTimeOfDayIndex == 1) 12 else 0
51 | }
52 | TimePickerTime(
53 | hour,
54 | it.minutes[it.selectedMinuteIndex].toInt()
55 | )
56 | }
57 | return time
58 | }
59 |
60 | fun updateUiState(
61 | timePickerTime: TimePickerTime,
62 | minuteGap: MinuteGap,
63 | is24: Boolean
64 | ) {
65 | _uiState.value = getUiStateTimeProvided(timePickerTime, minuteGap, is24)
66 | }
67 |
68 | fun getUiStateTimeProvided(
69 | timePickerTime: TimePickerTime,
70 | minuteGap: MinuteGap,
71 | is24: Boolean
72 | ): TimePickerUiState {
73 |
74 | if (timePickerTime.hour < 0 || timePickerTime.hour > 23) {
75 | throw IllegalArgumentException("Invalid hour: ${timePickerTime.hour}, The hour value must be between 0 and 23 inclusive.")
76 | }
77 | if (timePickerTime.minute < 0 || timePickerTime.minute > 59) {
78 | throw IllegalArgumentException("Invalid minute: ${timePickerTime.minute}, The minute value must be between 0 and 59 inclusive.")
79 | }
80 |
81 | val minute: Int = Constant.getNearestNextMinute(timePickerTime.minute, minuteGap)
82 | val hour: Int = timePickerTime.hour + if(minute == 0 && timePickerTime.minute != 0) 1 else 0
83 |
84 | return TimePickerUiState(
85 | is24Hour = is24,
86 | minuteGap = minuteGap,
87 | hours = Constant.getHours(is24),
88 | selectedHourIndex = Constant.getMiddleOfHour(is24) + hour,
89 | minutes = Constant.getMinutes(minuteGap),
90 | selectedMinuteIndex = Constant.getMiddleOfMinute(minuteGap) + minute / minuteGap.gap,
91 | timesOfDay = Constant.getTimesOfDay(),
92 | selectedTimeOfDayIndex = if (hour in 12..23) 1 else 0
93 | )
94 | }
95 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Left Arrow
4 |
--------------------------------------------------------------------------------
/composeDatePicker/src/test/java/com/vsnappy1/MainCoroutineRule.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1
2 |
3 | import kotlinx.coroutines.CoroutineDispatcher
4 | import kotlinx.coroutines.Dispatchers
5 | import kotlinx.coroutines.test.TestCoroutineScope
6 | import kotlinx.coroutines.test.resetMain
7 | import kotlinx.coroutines.test.setMain
8 | import org.junit.rules.TestWatcher
9 | import org.junit.runner.Description
10 | import kotlin.coroutines.ContinuationInterceptor
11 |
12 | class MainCoroutineRule: TestWatcher(), TestCoroutineScope by TestCoroutineScope() {
13 |
14 | override fun starting(description: Description) {
15 | super.starting(description)
16 | Dispatchers.setMain(
17 | this.coroutineContext[ContinuationInterceptor] as CoroutineDispatcher
18 | )
19 | }
20 |
21 | override fun finished(description: Description) {
22 | super.finished(description)
23 | Dispatchers.resetMain()
24 | }
25 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/test/java/com/vsnappy1/datepicker/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.datepicker
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/test/java/com/vsnappy1/datepicker/ui/viewmodel/DatePickerViewModelTest.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.datepicker.ui.viewmodel
2 |
3 | import android.icu.util.Calendar
4 | import androidx.arch.core.executor.testing.InstantTaskExecutorRule
5 | import com.vsnappy1.MainCoroutineRule
6 | import com.vsnappy1.datepicker.data.Constant
7 | import com.vsnappy1.datepicker.data.model.DatePickerDate
8 | import kotlinx.coroutines.ExperimentalCoroutinesApi
9 | import kotlinx.coroutines.test.advanceTimeBy
10 | import kotlinx.coroutines.test.runTest
11 | import org.junit.Assert.*
12 | import org.junit.Before
13 | import org.junit.Rule
14 | import org.junit.Test
15 | import org.junit.runner.RunWith
16 | import org.mockito.Mock
17 | import org.mockito.Mockito
18 | import org.mockito.junit.MockitoJUnitRunner
19 |
20 | @RunWith(MockitoJUnitRunner::class)
21 | class DatePickerViewModelTest {
22 |
23 | @get:Rule
24 | val instantExecutorRule = InstantTaskExecutorRule()
25 |
26 | @get:Rule
27 | val mainCoroutineRule = MainCoroutineRule()
28 |
29 | private lateinit var viewModel: DatePickerViewModel
30 |
31 | @Mock
32 | private lateinit var calendar: Calendar
33 |
34 | @Before
35 | fun setup() {
36 | viewModel = DatePickerViewModel()
37 | }
38 |
39 | @Test
40 | fun moveToNextMonth_when_selectedMonthIsNotDecember_yearShouldBeSame() {
41 | //Given
42 | viewModel.updateSelectedMonthIndex(0)
43 | val year = viewModel.uiState.value?.selectedYear
44 |
45 | //When
46 | viewModel.moveToNextMonth()
47 |
48 | //Then
49 | assertEquals(year, viewModel.uiState.value?.selectedYear)
50 | }
51 |
52 | @Test
53 | fun moveToNextMonth_when_selectedMonthIsDecember_yearShouldBeNextYear() {
54 | //Given
55 | viewModel.updateSelectedMonthIndex(11)
56 | val year = viewModel.uiState.value?.selectedYear
57 |
58 | //When
59 | viewModel.moveToNextMonth()
60 |
61 | //Then
62 | assertEquals(year?.plus(1), viewModel.uiState.value?.selectedYear)
63 | }
64 |
65 | @Test
66 | fun moveToNextMonth_when_selectedMonthIsDecemberAndYearIsTheLastYearInList_yearAndMonthShouldBeSame() {
67 | //Given
68 | viewModel.updateSelectedMonthIndex(11)
69 | viewModel.updateSelectedYearIndex(Constant.years.size - 1)
70 | val month = viewModel.uiState.value?.selectedMonth
71 | val year = viewModel.uiState.value?.selectedYear
72 |
73 | //When
74 | viewModel.moveToNextMonth()
75 |
76 | //Then
77 | assertEquals(year, viewModel.uiState.value?.selectedYear)
78 | assertEquals(month, viewModel.uiState.value?.selectedMonth)
79 | }
80 |
81 | @Test
82 | fun moveToPreviousMonth_when_selectedMonthIsNotJanuary_yearShouldBeSame() {
83 | //Given
84 | viewModel.updateSelectedMonthIndex(11)
85 | val year = viewModel.uiState.value?.selectedYear
86 |
87 | //When
88 | viewModel.moveToPreviousMonth()
89 |
90 | //Then
91 | assertEquals(year, viewModel.uiState.value?.selectedYear)
92 | }
93 |
94 | @Test
95 | fun moveToPreviousMonth_when_selectedMonthIsJanuary_yearShouldBePreviousYear() {
96 | //Given
97 | viewModel.updateSelectedMonthIndex(0)
98 | val year = viewModel.uiState.value?.selectedYear
99 |
100 | //When
101 | viewModel.moveToPreviousMonth()
102 |
103 | //Then
104 | assertEquals(year?.minus(1), viewModel.uiState.value?.selectedYear)
105 | }
106 |
107 | @Test
108 | fun moveToPreviousMonth_when_selectedMonthIsJanuaryAndYearIsTheFirstYearInList_yearAndMonthShouldBeSame() {
109 | //Given
110 | viewModel.updateSelectedMonthIndex(0)
111 | viewModel.updateSelectedYearIndex(0)
112 | val month = viewModel.uiState.value?.selectedMonth
113 | val year = viewModel.uiState.value?.selectedYear
114 |
115 | //When
116 | viewModel.moveToPreviousMonth()
117 |
118 | //Then
119 | assertEquals(year, viewModel.uiState.value?.selectedYear)
120 | assertEquals(month, viewModel.uiState.value?.selectedMonth)
121 | }
122 |
123 | @Test
124 | fun updateSelectedYearIndex_when_indexIsWithinRange_shouldUpdateTheSelectedYearAndCurrentVisibleMonth() {
125 | //Given
126 | viewModel.updateSelectedMonthIndex(0)
127 | viewModel.updateSelectedYearIndex(0)
128 | val currentVisibleMonth = viewModel.uiState.value?.currentVisibleMonth
129 | val year = viewModel.uiState.value?.selectedYear
130 |
131 | //When
132 | viewModel.updateSelectedYearIndex(5)
133 |
134 | //Then
135 | viewModel.uiState.value?.apply {
136 | assertEquals(currentVisibleMonth?.name, this.currentVisibleMonth.name)
137 | assertEquals(year?.plus(5), this.selectedYear)
138 | assertNotEquals(currentVisibleMonth, this.currentVisibleMonth)
139 | }
140 | }
141 |
142 | @Test
143 | fun toggleIsMonthYearViewVisible_when_isMonthYearViewVisibleIsFalse_shouldMakeIsMonthYearViewVisibleToTrue() {
144 | //Given
145 | viewModel.uiState.value?.copy(isMonthYearViewVisible = false)
146 | ?.let { viewModel.updateUiState(it) }
147 |
148 | //When
149 | viewModel.toggleIsMonthYearViewVisible()
150 |
151 | //Then
152 | assertTrue(viewModel.uiState.value?.isMonthYearViewVisible == true)
153 | }
154 |
155 | @OptIn(ExperimentalCoroutinesApi::class)
156 | @Test
157 | fun toggleIsMonthYearViewVisible_when_isMonthYearViewVisibleIsTrue_shouldMakeIsMonthYearViewVisibleToFalseAndUpdateSelectedMonthIndex() =
158 | runTest {
159 | //Given
160 | viewModel.uiState.value?.copy(isMonthYearViewVisible = true)
161 | ?.let {
162 | viewModel.updateUiState(it)
163 | viewModel.updateSelectedMonthIndex(5)
164 | }
165 |
166 | //When
167 | viewModel.toggleIsMonthYearViewVisible()
168 | advanceTimeBy(251)
169 |
170 | //Then
171 | assertTrue(viewModel.uiState.value?.isMonthYearViewVisible == false)
172 | assertEquals(
173 | Constant.getMiddleOfMonth() + 5,
174 | viewModel.uiState.value?.selectedMonthIndex,
175 | )
176 | }
177 |
178 | @Test(expected = IllegalArgumentException::class)
179 | fun setDate_when_givenYearIsNotWithinRange_shouldThrowAndIllegalArgumentException() {
180 | //Given
181 | val lastYear = Constant.years.last()
182 | val composeDatePickerDate = DatePickerDate(lastYear + 1, 0, 1)
183 |
184 | //When
185 | viewModel.setDate(composeDatePickerDate, calendar = calendar)
186 | }
187 |
188 | @Test(expected = IllegalArgumentException::class)
189 | fun setDate_when_givenMonthIsNotWithinRange_shouldThrowAndIllegalArgumentException() {
190 | //Given
191 | val lastYear = Constant.years.last()
192 | val composeDatePickerDate = DatePickerDate(lastYear, 12, 1)
193 |
194 | //When
195 | viewModel.setDate(composeDatePickerDate, calendar = calendar)
196 | }
197 |
198 | @Test(expected = IllegalArgumentException::class)
199 | fun setDate_when_givenDayIsZero_shouldThrowAndIllegalArgumentException() {
200 | //Given
201 | val lastYear = Constant.years.last()
202 | val composeDatePickerDate = DatePickerDate(lastYear, 5, 0)
203 |
204 | //When
205 | viewModel.setDate(composeDatePickerDate, calendar = calendar)
206 | }
207 |
208 | @Test(expected = IllegalArgumentException::class)
209 | fun setDate_when_givenDayIsMoreThenMaxDayOfMonth_shouldThrowAndIllegalArgumentException() {
210 | //Given
211 | val lastYear = Constant.years.last()
212 | val composeDatePickerDate = DatePickerDate(lastYear, 5, 31)
213 |
214 | //When
215 | viewModel.setDate(composeDatePickerDate, calendar = calendar)
216 | }
217 |
218 | @Test
219 | fun setDate_when_givenDateIsWithinRange_shouldUpdateTheSelectedYearSelectedMonthAndSelectedDay() {
220 | //Given
221 | viewModel.updateSelectedDayAndMonth(1)
222 | viewModel.updateSelectedMonthIndex(0)
223 | viewModel.updateSelectedYearIndex(0)
224 |
225 | val day = 7
226 | val month = 5
227 | val year = Constant.years.last()
228 | val composeDatePickerDate = DatePickerDate(year, month, day)
229 |
230 | Mockito.`when`(calendar.getActualMaximum(Calendar.DAY_OF_MONTH)).thenReturn(30)
231 |
232 | //When
233 | viewModel.setDate(composeDatePickerDate, calendar = calendar)
234 |
235 | //Then
236 | viewModel.uiState.value?.let {
237 | assertEquals(day, it.selectedDayOfMonth)
238 | assertEquals(month, it.selectedMonth.number)
239 | assertEquals(year, it.selectedYear)
240 | }
241 | }
242 | }
--------------------------------------------------------------------------------
/composeDatePicker/src/test/java/com/vsnappy1/timepicker/ui/viewmodel/TimePickerViewModelTest.kt:
--------------------------------------------------------------------------------
1 | package com.vsnappy1.timepicker.ui.viewmodel
2 |
3 | import androidx.arch.core.executor.testing.InstantTaskExecutorRule
4 | import com.vsnappy1.MainCoroutineRule
5 | import com.vsnappy1.timepicker.data.model.TimePickerTime
6 | import com.vsnappy1.timepicker.enums.MinuteGap
7 | import kotlinx.coroutines.ExperimentalCoroutinesApi
8 | import kotlinx.coroutines.test.advanceTimeBy
9 | import kotlinx.coroutines.test.runTest
10 | import org.junit.Assert.*
11 | import org.junit.Before
12 | import org.junit.Rule
13 | import org.junit.Test
14 | import org.junit.runner.RunWith
15 | import org.junit.runners.JUnit4
16 |
17 | @RunWith(JUnit4::class)
18 | class TimePickerViewModelTest {
19 |
20 | @get:Rule
21 | val instantTaskExecutorRule = InstantTaskExecutorRule()
22 |
23 | @get:Rule
24 | val mainCoroutineRule = MainCoroutineRule()
25 |
26 | private lateinit var viewModel: TimePickerViewModel
27 |
28 | @Before
29 | fun setup() {
30 | viewModel = TimePickerViewModel()
31 | }
32 |
33 | @Test(expected = IllegalArgumentException::class)
34 | fun getUiStateTimeProvided_when_hourIsLessThanZero_shouldThrowException() {
35 | //Given
36 | val time = TimePickerTime(-1, 45)
37 |
38 | //When
39 | viewModel.getUiStateTimeProvided(time, MinuteGap.FIVE, true)
40 | }
41 |
42 | @Test(expected = IllegalArgumentException::class)
43 | fun getUiStateTimeProvided_when_hourIsMoreThan23_shouldThrowException() {
44 | //Given
45 | val time = TimePickerTime(24, 45)
46 |
47 | //When
48 | viewModel.getUiStateTimeProvided(time, MinuteGap.FIVE, true)
49 | }
50 |
51 | @Test(expected = IllegalArgumentException::class)
52 | fun getUiStateTimeProvided_when_minuteIsLessThanZero_shouldThrowException() {
53 | //Given
54 | val time = TimePickerTime(12, -1)
55 |
56 | //When
57 | viewModel.getUiStateTimeProvided(time, MinuteGap.FIVE, true)
58 | }
59 |
60 | @Test(expected = IllegalArgumentException::class)
61 | fun getUiStateTimeProvided_when_minuteIsMoreThan59_shouldThrowException() {
62 | //Given
63 | val time = TimePickerTime(12, 60)
64 |
65 | //When
66 | viewModel.getUiStateTimeProvided(time, MinuteGap.FIVE, true)
67 | }
68 |
69 |
70 | @Test
71 | fun getUiStateTimeProvided_when_is24HourIsFalse_shouldUpdateTheUiStateAccordingly() {
72 | //Given
73 | val time = TimePickerTime(20, 55)
74 |
75 | //When
76 | viewModel.updateUiState(time, MinuteGap.FIVE, false)
77 |
78 | //Then
79 | viewModel.uiState.value?.let {
80 | val hour = it.hours[it.selectedHourIndex].toInt()
81 | val minute = it.minutes[it.selectedMinuteIndex].toInt()
82 | assertEquals(8, hour)
83 | assertEquals(55, minute)
84 | assertEquals(1, it.selectedTimeOfDayIndex)
85 | }
86 | }
87 |
88 | @Test
89 | fun getUiStateTimeProvided_when_is24HourIsTrue_shouldUpdateTheUiStateAccordingly() {
90 | //Given
91 | val time = TimePickerTime(20, 55)
92 |
93 | //When
94 | viewModel.updateUiState(time, MinuteGap.FIVE, true)
95 |
96 | //Then
97 | viewModel.uiState.value?.let {
98 | val hour = it.hours[it.selectedHourIndex].toInt()
99 | val minute = it.minutes[it.selectedMinuteIndex].toInt()
100 | assertEquals(20, hour)
101 | assertEquals(55, minute)
102 | }
103 | }
104 |
105 | @Test
106 | fun getUiStateTimeProvided_when_minuteProvidedIsNotMultipleOfMinuteGap_shouldUpdateTheUiStateAccordingly() {
107 | //Given
108 | val time = TimePickerTime(20, 51)
109 |
110 | //When
111 | viewModel.updateUiState(time, MinuteGap.FIVE, true)
112 |
113 | //Then
114 | viewModel.uiState.value?.let {
115 | val hour = it.hours[it.selectedHourIndex].toInt()
116 | val minute = it.minutes[it.selectedMinuteIndex].toInt()
117 | assertEquals(20, hour)
118 | assertEquals(55, minute)
119 | }
120 | }
121 |
122 | @OptIn(ExperimentalCoroutinesApi::class)
123 | @Test
124 | fun updateSelectedHourIndex_when_13HoursAdded_shouldChangeTimeOfDay() = runTest{
125 | //Given
126 | val time = TimePickerTime(0, 55)
127 |
128 | //When
129 | viewModel.updateUiState(time, MinuteGap.FIVE, false)
130 | viewModel.uiState.value?.let {
131 | viewModel.updateSelectedHourIndex(it.selectedHourIndex + 13)
132 | }
133 | advanceTimeBy(250)
134 |
135 | //Then
136 | viewModel.uiState.value?.let {
137 | assertEquals(1, it.selectedTimeOfDayIndex)
138 | }
139 | }
140 |
141 | @Test
142 | fun getSelectedTime_when_is24HourIsFalse_shouldReturnCorrectHoursAndMinutes() {
143 | //Given
144 | val time = TimePickerTime(20, 55)
145 |
146 | //When
147 | viewModel.updateUiState(time, MinuteGap.FIVE, false)
148 |
149 | //Then
150 | viewModel.getSelectedTime()?.let {
151 | assertEquals(20, it.hour)
152 | assertEquals(55, it.minute)
153 | }
154 | }
155 |
156 | @Test
157 | fun getSelectedTime_when_minuteGapIsFive_shouldCeilTheMinuteToNearestMultipleOfMinuteGap() {
158 | //Given
159 | val time = TimePickerTime(20, 53)
160 |
161 | //When
162 | viewModel.updateUiState(time, MinuteGap.FIVE, false)
163 |
164 | //Then
165 | viewModel.getSelectedTime()?.let {
166 | assertEquals(20, it.hour)
167 | assertEquals(55, it.minute)
168 | }
169 | }
170 |
171 | @Test
172 | fun getSelectedTime_when_minuteGapIsFiveAndCurrentMinuteIsMoreThan55_shouldMakeTheMinuteZeroAndIncrementTheHour() {
173 | //Given
174 | val time = TimePickerTime(20, 57)
175 |
176 | //When
177 | viewModel.updateUiState(time, MinuteGap.FIVE, false)
178 |
179 | //Then
180 | viewModel.getSelectedTime()?.let {
181 | assertEquals(21, it.hour)
182 | assertEquals(0, it.minute)
183 | }
184 | }
185 |
186 | @Test
187 | fun getSelectedTime_when_minuteGapIsFiveItIsElevenOClockAMAndCurrentMinuteIsMoreThan55_shouldMakeTheMinuteZeroAndIncrementTheHourAndChangeTimeOfTheDay() {
188 | //Given
189 | val time = TimePickerTime(11, 57)
190 |
191 | //When
192 | viewModel.updateUiState(time, MinuteGap.FIVE, false)
193 |
194 | //Then
195 | viewModel.getSelectedTime()?.let {
196 | assertEquals(12, it.hour)
197 | assertEquals(0, it.minute)
198 | }
199 | viewModel.uiState.value?.let {
200 | assertEquals(1, it.selectedTimeOfDayIndex)
201 | }
202 | }
203 | @Test
204 | fun getSelectedTime_when_minuteGapIsFiveItIsElevenOClockPMAndCurrentMinuteIsMoreThan55_shouldMakeTheMinuteZeroAndIncrementTheHourAndChangeTimeOfTheDay() {
205 | //Given
206 | val time = TimePickerTime(23, 57)
207 |
208 | //When
209 | viewModel.updateUiState(time, MinuteGap.FIVE, false)
210 |
211 | //Then
212 | viewModel.getSelectedTime()?.let {
213 | assertEquals(0, it.hour)
214 | assertEquals(0, it.minute)
215 | }
216 | viewModel.uiState.value?.let {
217 | assertEquals(0, it.selectedTimeOfDayIndex)
218 | }
219 | }
220 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vsnappy1/ComposeDatePicker/570dc841875f439ef6152820dba0466ae117683c/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Apr 20 23:50:23 CDT 2023
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/jitpack.yml:
--------------------------------------------------------------------------------
1 | jdk:
2 | - openjdk17
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google()
4 | mavenCentral()
5 | gradlePluginPortal()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | maven { url "https://jitpack.io" }
14 | }
15 | }
16 | rootProject.name = "ComposeCalendarExample"
17 | include ':app'
18 | include ':composeDatePicker'
19 |
--------------------------------------------------------------------------------