├── .github
└── workflows
│ └── android.yml
├── .gitignore
├── LICENSE.txt
├── README.md
├── app
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── akexorcist
│ │ └── snaptimepicker
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── akexorcist
│ │ │ └── snaptimepicker
│ │ │ └── sample
│ │ │ └── MainActivity.kt
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ ├── ic_launcher_background.xml
│ │ └── shape_gradient_bottom.xml
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── akexorcist
│ └── snaptimepicker
│ └── ExampleUnitTest.kt
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── image
├── 00_header.gif
├── 01_default.jpg
├── 02_text.jpg
├── 03_color.jpg
└── 04_time_range.jpg
├── publish
└── mavencentral.gradle
├── settings.gradle
└── snap-time-picker
├── build.gradle
├── gradle.properties
├── proguard-rules.pro
└── src
└── main
├── AndroidManifest.xml
├── java
└── com
│ └── akexorcist
│ └── snaptimepicker
│ ├── BaseSnapTimePickerDialogFragment.kt
│ ├── SnapTimePickerDialog.kt
│ ├── TimeNumberViewHolder.kt
│ ├── TimePickerAdapter.kt
│ ├── TimeRange.kt
│ ├── TimeValue.kt
│ └── extension
│ ├── SnapTimePickerUtil.kt
│ ├── SnapTimePickerViewModel.kt
│ ├── TimePickedEvent.kt
│ └── TimePickedLiveData.kt
└── res
├── drawable-v21
└── snap_time_picker_selector_button_translucent_black_round.xml
├── drawable
├── snap_time_picker_selector_button_translucent_black_round.xml
├── snap_time_picker_shadow_bottom_translucent_white.xml
├── snap_time_picker_shadow_top_translucent_white.xml
├── snap_time_picker_shape_background_white.xml
├── snap_time_picker_shape_button_disable_round.xml
├── snap_time_picker_shape_button_translucent_black_round_pressed.xml
└── snap_time_picker_shape_button_transparent_round_normal.xml
├── layout
├── layout_snap_time_picker_dialog.xml
└── layout_snap_time_picker_number_item.xml
└── values
├── colors.xml
├── dimens.xml
├── strings.xml
└── styles.xml
/.github/workflows/android.yml:
--------------------------------------------------------------------------------
1 | name: Android CI
2 |
3 | on:
4 | push:
5 | branches: [ master ]
6 | pull_request:
7 | branches: [ master ]
8 |
9 | jobs:
10 | test:
11 | name: Unit Test
12 | runs-on: ubuntu-latest
13 |
14 | steps:
15 | - uses: actions/checkout@v2
16 | - name: set up JDK 1.8
17 | uses: actions/setup-java@v1
18 | with:
19 | java-version: 1.8
20 | - name: Grant execute permission for gradlew
21 | run: chmod +x gradlew
22 |
23 | - name: Run Unit test
24 | run: ./gradlew test
25 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the ART/Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 | out/
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # Android Studio Navigation editor temp files
30 | .navigation/
31 |
32 | # Android Studio captures folder
33 | captures/
34 |
35 | # IntelliJ
36 | *.iml
37 | .idea/workspace.xml
38 | .idea/tasks.xml
39 | .idea/gradle.xml
40 | .idea/assetWizardSettings.xml
41 | .idea/dictionaries
42 | .idea/libraries
43 | .idea/caches
44 |
45 | # Keystore files
46 | # Uncomment the following line if you do not want to check your keystore files in.
47 | #*.jks
48 |
49 | # External native build folder generated in Android Studio 2.2 and later
50 | .externalNativeBuild
51 |
52 | # Google Services (e.g. APIs or Firebase)
53 | google-services.json
54 |
55 | # Freeline
56 | freeline.py
57 | freeline/
58 | freeline_project_description.json
59 |
60 | # fastlane
61 | fastlane/report.xml
62 | fastlane/Preview.html
63 | fastlane/screenshots
64 | fastlane/test_output
65 | fastlane/readme.md
66 | .idea
67 | *.gpg
68 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright 2019 Akexorcist
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://android-arsenal.com/details/1/8107)
2 | [](https://search.maven.org/artifact/com.akexorcist/snap-time-picker)
3 | 
4 | [](https://github.com/akexorcist/SnapTimePicker/actions)
5 |
6 | Snap Time Picker
7 | ==============================
8 | Another Material Time Picker for developer who do not like default Material Time Picker that difficult to use for most users
9 |
10 | 
11 |
12 | Download
13 | ===============================
14 | Since version 1.0.3 will [move from JCenter to MavenCentral](https://developer.android.com/studio/build/jcenter-migration)
15 | ```groovy
16 | // build.gradle (project)
17 | allprojects {
18 | repositories {
19 | mavenCentral()
20 | /* ... */
21 | }
22 | }
23 | ```
24 |
25 | **Gradle**
26 | ```
27 | implementation 'com.akexorcist:snap-time-picker:1.0.3'
28 | ```
29 |
30 | Feature
31 | ===========================
32 | * iOS Time Picker with Material Design style
33 | * Some text & color customization
34 | * Selectable time range support
35 | * ViewModel support for event callback with LiveData (See example)
36 |
37 | 
38 |
39 | Usage
40 | ===========================
41 | Relevant class in SnapTimePicker
42 | * SnapTimePickerDialog - Main Class
43 | * TimeValue - Time data holder that contain hour and minute
44 | * TimeRange - Time range data holder that contain the range of time with start (TimeValue) and end (TimeValue)
45 |
46 | To use the SnapTimePicker you have to create the SnapTimePickerDialog from builder
47 | ```kotlin
48 | val dialog = SnapTimePickerDialog.Builder().build()
49 | //
50 | dialog.show(supportFragmentManager, tag)
51 | ```
52 |
53 | SnapTimePickerDialog made from DialogFragment (AndroidX) so it need SupportFragmentManager from Activity/Fragment and any string tag. If you have no idea for the dialog tag. You can use `SnapTimePickerDialog.TAG`
54 |
55 | Note - Cannot reuse the SnapTimePickerDialog instance. Please create new instance every time
56 |
57 | To custom some text and color in TimePickerDialog.
58 | ```kotlin
59 | SnapTimePickerDialog.Builder().apply {
60 | setTitle(R.string.title)
61 | setPrefix(R.string.time_suffix)
62 | setSuffix(R.string.time_prefix)
63 | setThemeColor(R.color.colorAccent)
64 | setTitleColor(R.color.colorWhite)
65 | }.build().show(supportFragmentManager, tag)
66 | ```
67 |
68 | `Title`, `Prefix` and `Suffix` must be define with string resource. `ThemeColor` and `TitleColor` must be color resource
69 |
70 | 
71 |
72 | 
73 |
74 | To custom the positive and negative button.
75 | ```kotlin
76 | SnapTimePickerDialog.Builder().apply {
77 | setPositiveButtonText(R.string.accept)
78 | setNegativeButtonText(R.string.reject)
79 | setPositiveButtonColor(R.color.white)
80 | setNegativeButtonColor(R.color.white)
81 | setButtonTextAllCaps(false)
82 | }.build().show(supportFragmentManager, tag)
83 | ```
84 | Positive and negative button text will be all-capitalized by default.
85 |
86 | To set pre-selected time and time range in TimePickerDialog.
87 | ```kotlin
88 | SnapTimePickerDialog.Builder().apply {
89 | setPreselectedTime(TimeValue(2, 34))
90 | setSelectableTimeRange(TimeRange(TimeValue(2, 15), TimeValue(14, 30)))
91 | }.build().show(supportFragmentManager, tag)
92 | ```
93 |
94 | 
95 |
96 | For event callback from SnapTimePicker, you have assign the listener after build the SnapTimePickerDialog from builder.
97 | ```kotlin
98 | SnapTimePickerDialog.Builder().apply {
99 | //
100 | }.build().apply{
101 | setListener { hour, minute ->
102 | // Do something when user selected the time
103 | }
104 | }.show(supportFragmentManager, tag)
105 | ```
106 |
107 | But use listener does not good enough if the app can work in portrait and landscape. To support screen orientation, call `useViewModel()` in SnapTimePickerDialog then observe the event callback from SnapTimePicker's ViewModel from `SnapTimePickerUtil`
108 |
109 | ```kotlin
110 | SnapTimePickerDialog.Builder().apply {
111 | useViewModel()
112 | }.build().show(supportFragmentManager, SnapTimePickerDialog.TAG)
113 |
114 | SnapTimePickerUtil.observe(this) { selectedHour: Int, selectedMinute: Int ->
115 | onTimePicked(selectedHour, selectedMinute)
116 | }
117 | ```
118 |
119 | SnapTimePickerDialog can be called from anywhere in your code but `SnapTimePickerUtil.observe(...)` must called in `onCreate()` only (That's how ViewModel and LiveData works).
120 |
121 |
122 | Licence
123 | ===========================
124 | Copyright 2021 Akexorcist
125 |
126 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or at:
127 |
128 | http://www.apache.org/licenses/LICENSE-2.0
129 |
130 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
131 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-parcelize'
4 |
5 | android {
6 | compileSdkVersion project.compileSdkVersion
7 | defaultConfig {
8 | applicationId "com.akexorcist.snaptimepicker.sample"
9 | minSdkVersion project.minSdkVersion
10 | targetSdkVersion project.targetSdkVersion
11 | versionCode project.versionCode
12 | versionName project.versionName
13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
14 | }
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 | compileOptions {
22 | sourceCompatibility JavaVersion.VERSION_1_8
23 | targetCompatibility JavaVersion.VERSION_1_8
24 | }
25 | kotlinOptions {
26 | jvmTarget = '1.8'
27 | }
28 | buildFeatures {
29 | viewBinding = true
30 | }
31 | }
32 |
33 | dependencies {
34 | implementation fileTree(include: ['*.jar'], dir: 'libs')
35 | implementation project(':snap-time-picker')
36 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
37 | implementation 'androidx.appcompat:appcompat:1.2.0'
38 | implementation 'androidx.core:core-ktx:1.3.2'
39 | implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
40 | implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
41 | testImplementation 'junit:junit:4.13.2'
42 | androidTestImplementation 'androidx.test:runner:1.3.0'
43 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
44 | }
45 |
--------------------------------------------------------------------------------
/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
22 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/akexorcist/snaptimepicker/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.akexorcist.snaptimepicker
2 |
3 | import androidx.test.InstrumentationRegistry
4 | import androidx.test.runner.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.getTargetContext()
22 | assertEquals("com.akexorcist.snaptimepicker", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/java/com/akexorcist/snaptimepicker/sample/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.akexorcist.snaptimepicker.sample
2 |
3 | import android.os.Bundle
4 | import androidx.appcompat.app.AppCompatActivity
5 | import com.akexorcist.snaptimepicker.SnapTimePickerDialog
6 | import com.akexorcist.snaptimepicker.TimeRange
7 | import com.akexorcist.snaptimepicker.TimeValue
8 | import com.akexorcist.snaptimepicker.extension.SnapTimePickerUtil
9 | import com.akexorcist.snaptimepicker.sample.databinding.ActivityMainBinding
10 |
11 | class MainActivity : AppCompatActivity() {
12 | private val binding: ActivityMainBinding by lazy {
13 | ActivityMainBinding.inflate(layoutInflater)
14 | }
15 |
16 | override fun onCreate(savedInstanceState: Bundle?) {
17 | super.onCreate(savedInstanceState)
18 | setContentView(binding.root)
19 |
20 | binding.buttonNoCustomTimePicker.setOnClickListener {
21 | // No custom time picker
22 | SnapTimePickerDialog.Builder().apply {
23 | setTitle(R.string.title)
24 | setTitleColor(R.color.colorWhite)
25 | }.build().apply {
26 | setListener { hour, minute -> onTimePicked(hour, minute) }
27 | }.show(supportFragmentManager, SnapTimePickerDialog.TAG)
28 | }
29 |
30 | binding.buttonFullCustomTimePicker.setOnClickListener {
31 | // Custom text and color
32 | SnapTimePickerDialog.Builder().apply {
33 | setTitle(R.string.title)
34 | setPrefix(R.string.time_prefix)
35 | setSuffix(R.string.time_suffix)
36 | setThemeColor(R.color.colorAccent)
37 | setTitleColor(R.color.colorWhite)
38 | setNegativeButtonColor(android.R.color.holo_red_dark)
39 | setPositiveButtonColor(android.R.color.holo_blue_bright)
40 | setButtonTextAllCaps(false)
41 | }.build().apply {
42 | setListener { hour, minute -> onTimePicked(hour, minute) }
43 | }.show(supportFragmentManager, SnapTimePickerDialog.TAG)
44 | }
45 |
46 | binding.buttonPreselectedTime.setOnClickListener {
47 | // Set pre-selected time
48 | SnapTimePickerDialog.Builder().apply {
49 | setPreselectedTime(TimeValue(2, 15))
50 | }.build().apply {
51 | setListener { hour, minute -> onTimePicked(hour, minute) }
52 | }.show(supportFragmentManager, SnapTimePickerDialog.TAG)
53 | }
54 |
55 | binding.buttonTimeRange.setOnClickListener {
56 | // Set selectable time range
57 | SnapTimePickerDialog.Builder().apply {
58 | val start = TimeValue(2, 15)
59 | val end = TimeValue(14, 30)
60 | setSelectableTimeRange(TimeRange(start, end))
61 | }.build().apply {
62 | setListener { hour, minute -> onTimePicked(hour, minute) }
63 | }.show(supportFragmentManager, SnapTimePickerDialog.TAG)
64 | }
65 |
66 | binding.buttonTimeInterval.setOnClickListener {
67 | SnapTimePickerDialog.Builder().apply {
68 | setTimeInterval(7)
69 | setTitle(R.string.title)
70 | setTitleColor(R.color.colorWhite)
71 | }.build().apply {
72 | setListener { hour, minute -> onTimePicked(hour, minute) }
73 | }.show(supportFragmentManager, SnapTimePickerDialog.TAG)
74 | }
75 |
76 | binding.buttonViewModelCallback.setOnClickListener {
77 | // Get event callback from ViewModel observing. No need listener
78 | //
79 | // This very useful when you use ViewModel. Although user do
80 | // something that make configuration changes occur, you still get
81 | // event callback from LiveData.
82 | //
83 | // See how can you get event callback from ViewModel at line 85
84 | SnapTimePickerDialog.Builder().apply {
85 | useViewModel()
86 | }.build().show(supportFragmentManager, SnapTimePickerDialog.TAG)
87 | }
88 |
89 | // This code is work with `useViewModel()` at line 80
90 | SnapTimePickerUtil.observe(this) { selectedHour: Int, selectedMinute: Int ->
91 | onTimePicked(selectedHour, selectedMinute)
92 | }
93 | }
94 |
95 | private fun onTimePicked(selectedHour: Int, selectedMinute: Int) {
96 | val hour = selectedHour.toString().padStart(2, '0')
97 | val minute = selectedMinute.toString().padStart(2, '0')
98 | binding.textViewTime.text =
99 | String.format(getString(R.string.selected_time_format, hour, minute))
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
10 |
12 |
14 |
16 |
18 |
20 |
22 |
24 |
26 |
28 |
30 |
32 |
34 |
36 |
38 |
40 |
42 |
44 |
46 |
48 |
50 |
52 |
54 |
56 |
58 |
60 |
62 |
64 |
66 |
68 |
70 |
72 |
74 |
75 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/shape_gradient_bottom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
14 |
19 |
20 |
25 |
26 |
32 |
33 |
34 |
38 |
39 |
47 |
48 |
56 |
57 |
65 |
66 |
74 |
75 |
83 |
84 |
93 |
94 |
95 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 | #FFFFFF
7 |
8 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 8dp
4 | 16dp
5 | 24dp
6 | 32dp
7 | 16sp
8 | 48sp
9 | 8dp
10 | 200dp
11 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Snap Time Picker
3 | Please select the time
4 | Your selected time is
5 | -
6 | %1$s:%2$s
7 | >>
8 | <<
9 | No Custom
10 | Full Custom
11 | Pre-selected Time
12 | Time Range
13 | ViewModel Callback
14 | Time Interval
15 |
16 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/akexorcist/snaptimepicker/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.akexorcist.snaptimepicker
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 | }
18 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | project.ext {
3 | kotlin_version = '1.4.32'
4 | compileSdkVersion = 30
5 | targetSdkVersion = 30
6 | minSdkVersion = 18
7 |
8 | versionName = '1.0.3'
9 | versionCode = 10003
10 |
11 | libraryName = 'SnapTimePicker'
12 | libraryDescription = 'Another Material Time Picker for developer who do not like default Material Time Picker that difficult to use for most users'
13 |
14 | groupId = 'com.akexorcist'
15 | artifactId = 'snap-time-picker'
16 |
17 | siteUrl = 'https://github.com/akexorcist/Android-SnapTimePicker'
18 | gitUrl = 'https://github.com/akexorcist/Android-SnapTimePicker.git'
19 |
20 | developerId = 'akexorcist'
21 | developName = 'Somkiat Khitwongwattana'
22 | developerEmail = 'akexorcist@gmail.com'
23 |
24 | licenseName = 'The Apache License, Version 2.0'
25 | licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
26 | }
27 | repositories {
28 | google()
29 | jcenter()
30 |
31 | }
32 | dependencies {
33 | classpath 'com.android.tools.build:gradle:4.1.3'
34 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$project.kotlin_version"
35 | classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:0.9.17"
36 | }
37 | }
38 |
39 | allprojects {
40 | repositories {
41 | google()
42 | jcenter()
43 | }
44 | }
45 |
46 | task clean(type: Delete) {
47 | delete rootProject.buildDir
48 | }
--------------------------------------------------------------------------------
/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=-Xmx1536m
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 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Jan 10 00:57:30 ICT 2021
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/image/00_header.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/image/00_header.gif
--------------------------------------------------------------------------------
/image/01_default.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/image/01_default.jpg
--------------------------------------------------------------------------------
/image/02_text.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/image/02_text.jpg
--------------------------------------------------------------------------------
/image/03_color.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/image/03_color.jpg
--------------------------------------------------------------------------------
/image/04_time_range.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/image/04_time_range.jpg
--------------------------------------------------------------------------------
/publish/mavencentral.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'maven-publish'
2 | apply plugin: 'signing'
3 |
4 |
5 | task androidJavadocJar(type: Jar) {
6 | archiveClassifier.set('javadoc')
7 | from("$buildDir/javadoc")
8 | }
9 |
10 | task androidSourcesJar(type: Jar) {
11 | archiveClassifier.set('sources')
12 | if (project.plugins.findPlugin("com.android.library")) {
13 | from android.sourceSets.main.java.srcDirs
14 | from android.sourceSets.main.kotlin.srcDirs
15 | } else {
16 | from sourceSets.main.java.srcDirs
17 | from sourceSets.main.kotlin.srcDirs
18 | }
19 | }
20 |
21 | group = project.groupId
22 | version = project.versionName
23 |
24 | ext["signing.keyId"] = ''
25 | ext["signing.password"] = ''
26 | ext["signing.secretKeyRingFile"] = ''
27 | ext["ossrhUsername"] = ''
28 | ext["ossrhPassword"] = ''
29 | ext["sonatypeStagingProfileId"] = ''
30 |
31 | File secretPropsFile = project.rootProject.file('local.properties')
32 | if (secretPropsFile.exists()) {
33 | Properties p = new Properties()
34 | p.load(new FileInputStream(secretPropsFile))
35 | p.each { name, value ->
36 | ext[name] = value
37 | }
38 | } else {
39 | ext["signing.keyId"] = System.getenv('SIGNING_KEY_ID')
40 | ext["signing.password"] = System.getenv('SIGNING_PASSWORD')
41 | ext["signing.secretKeyRingFile"] = System.getenv('SIGNING_SECRET_KEY_RING_FILE')
42 | ext["ossrhUsername"] = System.getenv('OSSRH_USERNAME')
43 | ext["ossrhPassword"] = System.getenv('OSSRH_PASSWORD')
44 | ext["sonatypeStagingProfileId"] = System.getenv('SONATYPE_STAGING_PROFILE_ID')
45 | }
46 |
47 | publishing {
48 | publications {
49 | release(MavenPublication) {
50 | groupId project.groupId
51 | artifactId project.artifactId
52 | version project.versionName
53 |
54 | if (project.plugins.findPlugin("com.android.library")) {
55 | artifact("$buildDir/outputs/aar/${project.getName()}-release.aar")
56 | } else {
57 | artifact("$buildDir/libs/${project.getName()}-${version}.jar")
58 | }
59 |
60 | artifact androidJavadocJar
61 | artifact androidSourcesJar
62 |
63 | pom {
64 | name = project.libraryName
65 | description = project.libraryDescription
66 | url = project.siteUrl
67 | licenses {
68 | license {
69 | name = project.licenseName
70 | url = project.licenseUrl
71 | }
72 | }
73 | developers {
74 | developer {
75 | id = project.developerId
76 | name = project.developName
77 | email = project.developerEmail
78 | }
79 | }
80 | scm {
81 | connection = project.gitUrl
82 | developerConnection = project.gitUrl
83 | url = project.siteUrl
84 | }
85 | withXml {
86 | def dependenciesNode = asNode().appendNode('dependencies')
87 | project.configurations.implementation.allDependencies.each {
88 | if (it.name != 'unspecified') {
89 | def dependencyNode = dependenciesNode.appendNode('dependency')
90 | dependencyNode.appendNode('groupId', it.group)
91 | dependencyNode.appendNode('artifactId', it.name)
92 | dependencyNode.appendNode('version', it.version)
93 | }
94 | }
95 | }
96 | }
97 | }
98 | }
99 | repositories {
100 | maven {
101 | name = "sonatype"
102 | url = "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
103 | credentials {
104 | username ossrhUsername
105 | password ossrhPassword
106 | }
107 | }
108 | }
109 | }
110 |
111 | signing {
112 | sign publishing.publications
113 | }
114 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':snap-time-picker'
2 |
--------------------------------------------------------------------------------
/snap-time-picker/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-parcelize'
4 | apply plugin: 'org.jetbrains.dokka-android'
5 |
6 | android {
7 | compileSdkVersion project.compileSdkVersion
8 |
9 | defaultConfig {
10 | minSdkVersion project.minSdkVersion
11 | targetSdkVersion project.targetSdkVersion
12 | versionCode project.versionCode
13 | versionName project.versionName
14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | compileOptions {
23 | sourceCompatibility JavaVersion.VERSION_1_8
24 | targetCompatibility JavaVersion.VERSION_1_8
25 | }
26 | kotlinOptions {
27 | jvmTarget = '1.8'
28 | }
29 | buildFeatures {
30 | viewBinding = true
31 | }
32 | }
33 |
34 | dokka {
35 | outputFormat = 'html'
36 | outputDirectory = "$buildDir/javadoc"
37 | }
38 |
39 | dependencies {
40 | implementation fileTree(include: ['*.jar'], dir: 'libs')
41 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
42 | implementation 'androidx.appcompat:appcompat:1.2.0'
43 | implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
44 | implementation "androidx.recyclerview:recyclerview:1.2.0"
45 | implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
46 | }
47 |
48 | //apply from: '../publish/mavencentral.gradle'
49 |
--------------------------------------------------------------------------------
/snap-time-picker/gradle.properties:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akexorcist/SnapTimePicker/f724830f5ac27f38f7b524332b19f2f0664bd0ee/snap-time-picker/gradle.properties
--------------------------------------------------------------------------------
/snap-time-picker/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
22 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/java/com/akexorcist/snaptimepicker/BaseSnapTimePickerDialogFragment.kt:
--------------------------------------------------------------------------------
1 | package com.akexorcist.snaptimepicker
2 |
3 | import android.app.Dialog
4 | import android.graphics.Color
5 | import android.graphics.drawable.ColorDrawable
6 | import android.os.Bundle
7 | import android.view.LayoutInflater
8 | import android.view.View
9 | import android.view.Window
10 | import androidx.annotation.LayoutRes
11 | import androidx.appcompat.app.AlertDialog
12 | import androidx.fragment.app.DialogFragment
13 |
14 | abstract class BaseSnapTimePickerDialogFragment : DialogFragment() {
15 |
16 | lateinit var rootView: View
17 |
18 | override fun onCreate(savedInstanceState: Bundle?) {
19 | super.onCreate(savedInstanceState)
20 | savedInstanceState?.let { bundle ->
21 | restoreInstanceState(bundle)
22 | } ?: run {
23 | restoreArgument(arguments)
24 | }
25 | }
26 |
27 | override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
28 | val builder = AlertDialog.Builder(requireContext())
29 | val view = setupLayoutView()
30 | rootView = view
31 | builder.setView(view)
32 | val dialog = builder.create()
33 | dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
34 | dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
35 | return dialog
36 | }
37 |
38 | override fun onActivityCreated(savedInstanceState: Bundle?) {
39 | super.onActivityCreated(savedInstanceState)
40 | prepare()
41 | savedInstanceState?.let {
42 | restore()
43 | } ?: run {
44 | initialize()
45 | }
46 | setup()
47 | }
48 |
49 | override fun onSaveInstanceState(outState: Bundle) {
50 | super.onSaveInstanceState(outState)
51 | saveInstanceState(outState)
52 | }
53 |
54 | abstract fun setupLayoutView(): View
55 |
56 | abstract fun prepare()
57 |
58 | abstract fun restoreArgument(bundle: Bundle?)
59 |
60 | abstract fun initialize()
61 |
62 | abstract fun restoreInstanceState(savedInstanceState: Bundle?)
63 |
64 | abstract fun restore()
65 |
66 | abstract fun saveInstanceState(outState: Bundle?)
67 |
68 | abstract fun setup()
69 | }
70 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/java/com/akexorcist/snaptimepicker/SnapTimePickerDialog.kt:
--------------------------------------------------------------------------------
1 | package com.akexorcist.snaptimepicker
2 |
3 | import android.app.Activity
4 | import android.content.Intent
5 | import android.os.Bundle
6 | import android.os.Handler
7 | import android.os.Looper
8 | import android.view.LayoutInflater
9 | import android.view.View
10 | import androidx.annotation.ColorRes
11 | import androidx.annotation.StringRes
12 | import androidx.core.content.ContextCompat
13 | import androidx.lifecycle.ViewModelProvider
14 | import androidx.recyclerview.widget.LinearLayoutManager
15 | import androidx.recyclerview.widget.LinearSnapHelper
16 | import androidx.recyclerview.widget.RecyclerView
17 | import com.akexorcist.snaptimepicker.databinding.LayoutSnapTimePickerDialogBinding
18 | import com.akexorcist.snaptimepicker.extension.SnapTimePickerViewModel
19 |
20 | @Suppress("unused")
21 | class SnapTimePickerDialog : BaseSnapTimePickerDialogFragment() {
22 | private val binding: LayoutSnapTimePickerDialogBinding by lazy {
23 | LayoutSnapTimePickerDialogBinding.inflate(LayoutInflater.from(requireContext()))
24 | }
25 |
26 | private lateinit var hourAdapter: TimePickerAdapter
27 | private lateinit var minuteAdapter: TimePickerAdapter
28 | private lateinit var hourLayoutManager: LinearLayoutManager
29 | private lateinit var minuteLayoutManager: LinearLayoutManager
30 | private lateinit var hourSnapHelper: LinearSnapHelper
31 | private lateinit var minuteSnapHelper: LinearSnapHelper
32 |
33 | private lateinit var hourList: List
34 | private lateinit var minuteList: List
35 |
36 | private var selectableTimeRange: TimeRange? = null
37 | private var preselectedTime: TimeValue? = null
38 | private var isUseViewModel = false
39 | private var title: Int = -1
40 | private var prefix: Int = -1
41 | private var suffix: Int = -1
42 | private var titleColor: Int = -1
43 | private var themeColor: Int = -1
44 | private var negativeButtonText: Int = -1
45 | private var positiveButtonText: Int = -1
46 | private var negativeButtonColor: Int = -1
47 | private var positiveButtonColor: Int = -1
48 | private var buttonTextAllCaps = true
49 | private var timeInterval: Int = 1
50 | private var listener: Listener? = null
51 |
52 | private var lastSelectedHour = -1
53 | private var lastSelectedMinute = -1
54 |
55 | companion object {
56 | private const val EXTRA_SELECTABLE_TIME_RANGE = "com.akexorcist.snaptimepicker.selectable_time_range"
57 | private const val EXTRA_PRESELECTED_TIME = "com.akexorcist.snaptimepicker.preselected_time"
58 | private const val EXTRA_SELECTED_HOUR = "com.akexorcist.snaptimepicker.selected_hour"
59 | private const val EXTRA_SELECTED_MINUTE = "com.akexorcist.snaptimepicker.selected_minute"
60 | private const val EXTRA_IS_USE_VIEW_MODEL = "com.akexorcist.snaptimepicker.is_use_view_model"
61 | private const val EXTRA_TITLE = "com.akexorcist.snaptimepicker.title"
62 | private const val EXTRA_SUFFIX = "com.akexorcist.snaptimepicker.suffix"
63 | private const val EXTRA_PREFIX = "com.akexorcist.snaptimepicker.prefix"
64 | private const val EXTRA_TITLE_COLOR = "com.akexorcist.snaptimepicker.title_color"
65 | private const val EXTRA_THEME_COLOR = "com.akexorcist.snaptimepicker.theme_color"
66 | private const val EXTRA_NEGATIVE_BUTTON_TEXT = "com.akexorcist.snaptimepicker.negative_button_text"
67 | private const val EXTRA_POSITIVE_BUTTON_TEXT = "com.akexorcist.snaptimepicker.positive_button_text"
68 | private const val EXTRA_NEGATIVE_BUTTON_COLOR = "com.akexorcist.snaptimepicker.negative_button_color"
69 | private const val EXTRA_POSITIVE_BUTTON_COLOR = "com.akexorcist.snaptimepicker.positive_button_color"
70 | private const val EXTRA_BUTTON_TEXT_ALL_CAPS = "com.akexorcist.snaptimepicker.button_text_all_caps"
71 | private const val EXTRA_TIME_INTERVAL = "com.akexorcist.snaptimepicker.time_interval"
72 | private const val MIN_HOUR = 0
73 | private const val MAX_HOUR = 23
74 | private const val MIN_MINUTE = 0
75 | private const val MAX_MINUTE = 59
76 | private const val MINUTE_IN_HOUR = 60
77 | private const val UPDATE_PRE_SELECTED_START_TIME = 100L
78 | const val TAG = "SnapTimePickerDialog"
79 |
80 | private fun newInstance(
81 | selectableTimeRange: TimeRange?,
82 | preselectedTime: TimeValue?,
83 | isUseViewModel: Boolean,
84 | title: Int,
85 | prefix: Int,
86 | suffix: Int,
87 | titleColor: Int,
88 | themeColor: Int,
89 | negativeButtonText: Int,
90 | positiveButtonText: Int,
91 | negativeButtonColor: Int,
92 | positiveButtonColor: Int,
93 | buttonTextAllCaps: Boolean,
94 | timeInterval: Int
95 | ): SnapTimePickerDialog = SnapTimePickerDialog().apply {
96 | isCancelable = false
97 | arguments = Bundle().apply {
98 | putParcelable(EXTRA_SELECTABLE_TIME_RANGE, selectableTimeRange)
99 | putParcelable(EXTRA_PRESELECTED_TIME, preselectedTime)
100 | putBoolean(EXTRA_IS_USE_VIEW_MODEL, isUseViewModel)
101 | putInt(EXTRA_TITLE, title)
102 | putInt(EXTRA_PREFIX, prefix)
103 | putInt(EXTRA_SUFFIX, suffix)
104 | putInt(EXTRA_TITLE_COLOR, titleColor)
105 | putInt(EXTRA_THEME_COLOR, themeColor)
106 | putInt(EXTRA_NEGATIVE_BUTTON_TEXT, negativeButtonText)
107 | putInt(EXTRA_POSITIVE_BUTTON_TEXT, positiveButtonText)
108 | putInt(EXTRA_NEGATIVE_BUTTON_COLOR, negativeButtonColor)
109 | putInt(EXTRA_POSITIVE_BUTTON_COLOR, positiveButtonColor)
110 | putBoolean(EXTRA_BUTTON_TEXT_ALL_CAPS, buttonTextAllCaps)
111 | putInt(EXTRA_TIME_INTERVAL, timeInterval)
112 | }
113 | }
114 | }
115 |
116 | override fun setupLayoutView(): View = binding.root
117 |
118 | override fun prepare() {
119 | run {
120 | hourAdapter = TimePickerAdapter()
121 | minuteAdapter = TimePickerAdapter()
122 | hourLayoutManager = LinearLayoutManager(context)
123 | minuteLayoutManager = LinearLayoutManager(context)
124 | hourSnapHelper = LinearSnapHelper()
125 | minuteSnapHelper = LinearSnapHelper()
126 | binding.recyclerViewHour.layoutManager = hourLayoutManager
127 | binding.recyclerViewHour.adapter = hourAdapter
128 | hourSnapHelper.attachToRecyclerView(binding.recyclerViewHour)
129 | binding.recyclerViewMinute.layoutManager = minuteLayoutManager
130 | binding.recyclerViewMinute.adapter = minuteAdapter
131 | minuteSnapHelper.attachToRecyclerView(binding.recyclerViewMinute)
132 | if (title != -1) {
133 | binding.textViewTitle.text = getString(title)
134 | }
135 | if (prefix != -1) {
136 | binding.textViewTimePrefix.text = getString(prefix)
137 | }
138 | if (suffix != -1) {
139 | binding.textViewTimeSuffix.text = getString(suffix)
140 | }
141 | if (titleColor != -1) {
142 | context?.let { context ->
143 | binding.textViewTitle.setTextColor(
144 | ContextCompat.getColor(
145 | context,
146 | titleColor
147 | )
148 | )
149 | }
150 | }
151 | if (themeColor != -1) {
152 | context?.let { context ->
153 | binding.buttonConfirm.setTextColor(ContextCompat.getColor(context, themeColor))
154 | binding.buttonCancel.setTextColor(ContextCompat.getColor(context, themeColor))
155 | binding.textViewTitle.setBackgroundColor(
156 | ContextCompat.getColor(context, themeColor)
157 | )
158 | }
159 | }
160 | if (positiveButtonText != -1) {
161 | binding.buttonConfirm.text = getString(positiveButtonText)
162 | }
163 | if (negativeButtonText != -1) {
164 | binding.buttonCancel.text = getString(negativeButtonText)
165 | }
166 |
167 | if (negativeButtonColor != -1) {
168 | context?.let { context ->
169 | binding.buttonCancel.setTextColor(ContextCompat.getColor(context, negativeButtonColor))
170 | }
171 | }
172 |
173 | if (positiveButtonColor != -1) {
174 | context?.let { context ->
175 | binding.buttonConfirm.setTextColor(ContextCompat.getColor(context, positiveButtonColor))
176 | }
177 | }
178 |
179 | run {
180 | binding.buttonConfirm.isAllCaps = buttonTextAllCaps
181 | binding.buttonCancel.isAllCaps = buttonTextAllCaps
182 | binding.buttonConfirm.setOnClickListener { onConfirmClick() }
183 | binding.buttonCancel.setOnClickListener { onCancelClick() }
184 | binding.recyclerViewHour.addOnScrollListener(hourScrollListener)
185 | binding.recyclerViewMinute.addOnScrollListener(minuteScrollListener)
186 | }
187 | run {
188 | resetPreselectedTimeWhenNeed()
189 | setupTimePicker()
190 | if (isUseViewModel) {
191 | useLiveDataAsCallback()
192 | }
193 | }
194 | }
195 | }
196 |
197 | override fun restoreArgument(bundle: Bundle?) {
198 | selectableTimeRange = bundle?.getParcelable(EXTRA_SELECTABLE_TIME_RANGE)
199 | preselectedTime = bundle?.getParcelable(EXTRA_PRESELECTED_TIME)
200 | isUseViewModel = bundle?.getBoolean(EXTRA_IS_USE_VIEW_MODEL) ?: false
201 | title = bundle?.getInt(EXTRA_TITLE, -1) ?: -1
202 | prefix = bundle?.getInt(EXTRA_PREFIX, -1) ?: -1
203 | suffix = bundle?.getInt(EXTRA_SUFFIX, -1) ?: -1
204 | themeColor = bundle?.getInt(EXTRA_THEME_COLOR, -1) ?: -1
205 | titleColor = bundle?.getInt(EXTRA_TITLE_COLOR, -1) ?: -1
206 | negativeButtonText = bundle?.getInt(EXTRA_NEGATIVE_BUTTON_TEXT, -1) ?: -1
207 | positiveButtonText = bundle?.getInt(EXTRA_POSITIVE_BUTTON_TEXT, -1) ?: -1
208 | negativeButtonColor = bundle?.getInt(EXTRA_NEGATIVE_BUTTON_COLOR, -1) ?: -1
209 | positiveButtonColor = bundle?.getInt(EXTRA_POSITIVE_BUTTON_COLOR, -1) ?: -1
210 | buttonTextAllCaps = bundle?.getBoolean(EXTRA_BUTTON_TEXT_ALL_CAPS, true) ?: true
211 | timeInterval = bundle?.getInt(EXTRA_TIME_INTERVAL, 1) ?: 1
212 | }
213 |
214 | override fun initialize() {
215 | setupPreselectedTime()
216 | }
217 |
218 | override fun restoreInstanceState(savedInstanceState: Bundle?) {
219 | selectableTimeRange = savedInstanceState?.getParcelable(EXTRA_SELECTABLE_TIME_RANGE)
220 | preselectedTime = savedInstanceState?.getParcelable(EXTRA_PRESELECTED_TIME)
221 | lastSelectedHour = savedInstanceState?.getInt(EXTRA_SELECTED_HOUR, -1) ?: -1
222 | lastSelectedMinute = savedInstanceState?.getInt(EXTRA_SELECTED_MINUTE, -1) ?: -1
223 | isUseViewModel = savedInstanceState?.getBoolean(EXTRA_IS_USE_VIEW_MODEL) ?: false
224 | title = savedInstanceState?.getInt(EXTRA_TITLE, -1) ?: -1
225 | prefix = savedInstanceState?.getInt(EXTRA_PREFIX, -1) ?: -1
226 | suffix = savedInstanceState?.getInt(EXTRA_SUFFIX, -1) ?: -1
227 | themeColor = savedInstanceState?.getInt(EXTRA_THEME_COLOR, -1) ?: -1
228 | titleColor = savedInstanceState?.getInt(EXTRA_TITLE_COLOR, -1) ?: -1
229 | negativeButtonText = savedInstanceState?.getInt(EXTRA_NEGATIVE_BUTTON_TEXT, -1) ?: -1
230 | positiveButtonText = savedInstanceState?.getInt(EXTRA_POSITIVE_BUTTON_TEXT, -1) ?: -1
231 | negativeButtonColor = savedInstanceState?.getInt(EXTRA_NEGATIVE_BUTTON_COLOR, -1) ?: -1
232 | positiveButtonColor = savedInstanceState?.getInt(EXTRA_POSITIVE_BUTTON_COLOR, -1) ?: -1
233 | buttonTextAllCaps = savedInstanceState?.getBoolean(EXTRA_BUTTON_TEXT_ALL_CAPS, true) ?: true
234 | timeInterval = savedInstanceState?.getInt(EXTRA_TIME_INTERVAL, 1) ?: 1
235 | }
236 |
237 | override fun restore() {
238 | setupPreselectedTime(TimeValue(lastSelectedHour, lastSelectedMinute))
239 | updateSelectableTime(lastSelectedHour, lastSelectedMinute)
240 | }
241 |
242 | override fun saveInstanceState(outState: Bundle?) {
243 | outState?.putParcelable(EXTRA_SELECTABLE_TIME_RANGE, selectableTimeRange)
244 | outState?.putParcelable(EXTRA_PRESELECTED_TIME, preselectedTime)
245 | outState?.putInt(EXTRA_SELECTED_HOUR, lastSelectedHour)
246 | outState?.putInt(EXTRA_SELECTED_MINUTE, lastSelectedMinute)
247 | outState?.putBoolean(EXTRA_IS_USE_VIEW_MODEL, isUseViewModel)
248 | outState?.putInt(EXTRA_TITLE, title)
249 | outState?.putInt(EXTRA_PREFIX, prefix)
250 | outState?.putInt(EXTRA_SUFFIX, suffix)
251 | outState?.putInt(EXTRA_THEME_COLOR, themeColor)
252 | outState?.putInt(EXTRA_TITLE_COLOR, titleColor)
253 | outState?.putInt(EXTRA_NEGATIVE_BUTTON_TEXT, negativeButtonText)
254 | outState?.putInt(EXTRA_POSITIVE_BUTTON_TEXT, positiveButtonText)
255 | outState?.putInt(EXTRA_NEGATIVE_BUTTON_COLOR, negativeButtonColor)
256 | outState?.putInt(EXTRA_POSITIVE_BUTTON_COLOR, positiveButtonColor)
257 | outState?.putBoolean(EXTRA_BUTTON_TEXT_ALL_CAPS, buttonTextAllCaps)
258 | outState?.putInt(EXTRA_TIME_INTERVAL, timeInterval)
259 | }
260 |
261 | override fun setup() {}
262 |
263 | override fun onDestroy() {
264 | super.onDestroy()
265 | binding.recyclerViewHour.removeOnScrollListener(hourScrollListener)
266 | binding.recyclerViewMinute.removeOnScrollListener(minuteScrollListener)
267 | }
268 |
269 | private val hourScrollListener = object : RecyclerView.OnScrollListener() {
270 | override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
271 | super.onScrollStateChanged(recyclerView, newState)
272 | if (newState == RecyclerView.SCROLL_STATE_IDLE) {
273 | var currentSelectedHour = -1
274 | val hourSnappedView = hourSnapHelper.findSnapView(hourLayoutManager)
275 | hourSnappedView?.let { view ->
276 | currentSelectedHour =
277 | hourAdapter.getValueByPosition(hourLayoutManager.getPosition(view))
278 | }
279 | updateSelectableTime(currentSelectedHour, lastSelectedMinute)
280 | lastSelectedHour = currentSelectedHour
281 | }
282 | }
283 | }
284 |
285 | private val minuteScrollListener = object : RecyclerView.OnScrollListener() {
286 | override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
287 | super.onScrollStateChanged(recyclerView, newState)
288 | if (newState == RecyclerView.SCROLL_STATE_IDLE) {
289 | var currentSelectedMinute = -1
290 | val minuteSnappedView = minuteSnapHelper.findSnapView(minuteLayoutManager)
291 | minuteSnappedView?.let { view ->
292 | currentSelectedMinute =
293 | minuteAdapter.getValueByPosition(minuteLayoutManager.getPosition(view))
294 | }
295 | updateSelectableTime(lastSelectedHour, currentSelectedMinute)
296 | lastSelectedMinute = currentSelectedMinute
297 | }
298 | }
299 | }
300 |
301 | fun setListener(listener: Listener?) {
302 | this.listener = listener
303 | }
304 |
305 | fun setListener(onTimePicked: (hour: Int, minute: Int) -> Unit) {
306 | this.listener = object : Listener {
307 | override fun onTimePicked(hour: Int, minute: Int) {
308 | onTimePicked(hour, minute)
309 | }
310 | }
311 | }
312 |
313 | fun isUseViewModel(): Boolean = isUseViewModel
314 |
315 | fun getTitleResourceId(): Int = title
316 |
317 | fun getTitle(): String = getString(title)
318 |
319 | fun getPrefixResourceId(): Int = prefix
320 |
321 | fun getPrefix(): String = getString(prefix)
322 |
323 | fun getSuffixResourceId(): Int = suffix
324 |
325 | fun getSuffix(): String = getString(suffix)
326 |
327 | fun getTitleColorResourceId(): Int = titleColor
328 |
329 | fun getTitleColor(): Int = context?.let { context ->
330 | ContextCompat.getColor(context, titleColor)
331 | } ?: -1
332 |
333 | fun getThemeColorResourceId(): Int = themeColor
334 |
335 | fun getThemeColor(): Int = context?.let { context ->
336 | ContextCompat.getColor(context, themeColor)
337 | } ?: -1
338 |
339 | fun getNegativeButtonText(): String = getString(negativeButtonText)
340 |
341 | fun getPositiveButtonText(): String = getString(positiveButtonText)
342 |
343 | fun getNegativeButtonColorResourceId(): Int = negativeButtonColor
344 |
345 | fun getNegativeButtonColor(): Int = context?.let { context ->
346 | ContextCompat.getColor(context, negativeButtonColor)
347 | } ?: -1
348 |
349 | fun getPositiveButtonColorResourceId(): Int = positiveButtonColor
350 |
351 | fun getPositiveButtonColor(): Int = context?.let { context ->
352 | ContextCompat.getColor(context, positiveButtonColor)
353 | } ?: -1
354 |
355 | fun isButtonTextAllCaps(): Boolean = buttonTextAllCaps
356 |
357 | private fun updateSelectableTime(currentSelectedHour: Int, currentSelectedMinute: Int) {
358 | if (currentSelectedHour != -1 && currentSelectedMinute != -1) {
359 | if (currentSelectedHour == selectableTimeRange?.start?.hour) {
360 | val startMinute = selectableTimeRange?.start?.minute ?: -1
361 | val endMinute = MAX_MINUTE
362 | updateMinuteListWithRange(startMinute, endMinute)
363 | val minutePosition = minuteAdapter.getPositionByValue(currentSelectedMinute)
364 | if (currentSelectedMinute < startMinute) {
365 | updateMinutePosition(minutePosition)
366 | }
367 | } else if (currentSelectedHour == selectableTimeRange?.end?.hour) {
368 | val startMinute = MIN_MINUTE
369 | val endMinute = selectableTimeRange?.end?.minute ?: -1
370 | updateMinuteListWithRange(startMinute, endMinute)
371 | if (currentSelectedMinute > endMinute) {
372 | updateMinutePosition(currentSelectedMinute)
373 | }
374 | } else if (currentSelectedHour != selectableTimeRange?.start?.hour &&
375 | currentSelectedHour != selectableTimeRange?.end?.hour &&
376 | minuteList.size < MAX_MINUTE + 1
377 | ) {
378 | initMinuteList(true)
379 | }
380 | }
381 | }
382 |
383 | private fun setupTimePicker() {
384 | iniHourList()
385 | initMinuteList(false)
386 | }
387 |
388 | private fun iniHourList() {
389 | val startHour = selectableTimeRange?.start?.hour ?: -1
390 | val endHour = selectableTimeRange?.end?.hour ?: -1
391 | this.hourList = listOf()
392 | if (isEarlierSelectableTime()) {
393 | for (index in MIN_HOUR..MAX_HOUR) {
394 | if (startHour != -1 && endHour != -1) {
395 | if (index in startHour..endHour) {
396 | hourList = hourList + index
397 | }
398 | } else {
399 | hourList = hourList + index
400 | }
401 | }
402 | } else if (isLaterSelectableTime()) {
403 | if (startHour != -1 && endHour != -1) {
404 | for (index in startHour..MAX_HOUR) {
405 | if (index in startHour..MAX_HOUR || index in MIN_HOUR..endHour) {
406 | hourList = hourList + index
407 | }
408 | }
409 | for (index in MIN_HOUR..endHour) {
410 | if (index in startHour..MAX_HOUR || index in MIN_HOUR..endHour) {
411 | hourList = hourList + index
412 | }
413 | }
414 | } else {
415 | for (index in MIN_HOUR..MAX_HOUR) {
416 | hourList = hourList + index
417 | }
418 | }
419 | } else {
420 | if (startHour != -1 && endHour != -1) {
421 | hourList = hourList + startHour
422 | } else {
423 | for (index in MIN_HOUR..MAX_HOUR) {
424 | hourList = hourList + index
425 | }
426 | }
427 | }
428 | hourAdapter.setItemList(hourList)
429 | }
430 |
431 | private fun initMinuteList(includeAll: Boolean) {
432 | this.minuteList = listOf()
433 | for (index in MIN_MINUTE until (MINUTE_IN_HOUR / timeInterval)) {
434 | minuteList = minuteList + index * this.timeInterval
435 | }
436 | minuteAdapter.setItemList(minuteList)
437 | if (!includeAll && preselectedTime != null &&
438 | isInTimeRange(preselectedTime, selectableTimeRange)
439 | ) {
440 | preselectedTime?.let { time ->
441 | updateSelectableTime(time.hour, time.minute)
442 | }
443 | }
444 | }
445 |
446 | private fun isInTimeRange(time: TimeValue?, timeRange: TimeRange?): Boolean {
447 | val startHour = timeRange?.start?.hour ?: -1
448 | val startMinute = timeRange?.start?.minute ?: -1
449 | val endHour = timeRange?.end?.hour ?: -1
450 | val endMinute = timeRange?.end?.minute ?: -1
451 | val expectHour = time?.hour ?: -1
452 | val expectMinute = time?.minute ?: -1
453 | if (time == null || timeRange == null ||
454 | startHour == -1 || startMinute == -1 ||
455 | endHour == -1 || endMinute == -1 ||
456 | expectHour == -1 || expectMinute == -1
457 | ) {
458 | return false
459 | }
460 | return if (startHour < endHour || (startHour == endHour && startMinute < endMinute)) {
461 | (expectHour in (startHour + 1) until endHour) ||
462 | (expectHour == startHour && expectMinute >= startMinute) ||
463 | (expectHour == endHour && expectMinute <= endMinute)
464 | } else if (startHour > endHour || (startHour == endHour && startHour > endHour)) {
465 | (expectHour in (endHour + 1) until startHour) ||
466 | (expectHour == endHour && expectMinute >= endMinute) ||
467 | (expectHour == startHour && expectMinute <= startMinute)
468 | } else {
469 | expectHour == startHour && expectMinute == startMinute
470 | }
471 | }
472 |
473 | private fun updateMinuteListWithRange(startMinute: Int, endMinute: Int) {
474 | this.minuteList = listOf()
475 | for (index in MIN_MINUTE..MAX_MINUTE) {
476 | if (startMinute != -1 && endMinute != -1) {
477 | if (index in startMinute..endMinute) {
478 | minuteList = minuteList + index
479 | }
480 | } else {
481 | minuteList = minuteList + index
482 | }
483 | }
484 | minuteAdapter.setItemList(minuteList)
485 | }
486 |
487 | private fun resetPreselectedTimeWhenNeed() {
488 | if (preselectedTime != null && selectableTimeRange != null) {
489 | preselectedTime?.let {
490 | selectableTimeRange?.let { timeRange ->
491 | if (shouldResetPreselectedTime()) {
492 | timeRange.start?.let { start ->
493 | preselectedTime?.hour = start.hour
494 | preselectedTime?.minute = start.minute
495 | }
496 | }
497 | }
498 | }
499 | }
500 | }
501 |
502 | private fun shouldResetPreselectedTime(): Boolean {
503 | val startHour = selectableTimeRange?.start?.hour ?: -1
504 | val startMinute = selectableTimeRange?.start?.minute ?: -1
505 | val endHour = selectableTimeRange?.end?.hour ?: -1
506 | val endMinute = selectableTimeRange?.end?.minute ?: -1
507 | val preSelectedHour = preselectedTime?.hour ?: -1
508 | val preSelectedMinute = preselectedTime?.minute ?: -1
509 | return when {
510 | isEarlierSelectableTime() -> preSelectedHour < startHour || preSelectedHour > endHour ||
511 | (preSelectedHour == startHour && preSelectedMinute < startMinute) ||
512 | (preSelectedHour == endHour && preSelectedMinute > endMinute)
513 | isLaterSelectableTime() -> (preSelectedHour in (endHour + 1) until startHour) ||
514 | (preSelectedHour == startHour && preSelectedMinute < startMinute) ||
515 | (preSelectedHour == endHour && preSelectedMinute > endMinute)
516 | else -> false
517 | }
518 | }
519 |
520 | private fun setupPreselectedTime(selectedTime: TimeValue? = preselectedTime) {
521 | binding.recyclerViewHour.scrollToPosition(1)
522 | binding.recyclerViewMinute.scrollToPosition(1)
523 | selectedTime?.let { time ->
524 | val selectedHour = time.hour
525 | val selectedMinute = time.minute
526 | val hourPosition = hourAdapter.getPositionByValue(selectedHour)
527 | val minutePosition = minuteAdapter.getPositionByValue(selectedMinute)
528 | updateHourPosition(if (hourPosition != -1) hourPosition else 0)
529 | updateMinutePosition(if (minutePosition != -1) minutePosition else 0)
530 | } ?: run {
531 | updateHourPosition(0)
532 | updateMinutePosition(0)
533 | }
534 | }
535 |
536 | private fun updateHourPosition(hourPosition: Int) {
537 | try {
538 | Handler(Looper.getMainLooper()).postDelayed({
539 | if (hourPosition != -1) {
540 | binding.recyclerViewHour.smoothScrollToPosition(hourPosition)
541 | }
542 | }, UPDATE_PRE_SELECTED_START_TIME)
543 | } catch (ignored: IllegalArgumentException) {
544 | }
545 | }
546 |
547 | private fun updateMinutePosition(minutePosition: Int) {
548 | try {
549 | Handler(Looper.getMainLooper()).postDelayed({
550 | if (minutePosition != -1) {
551 | binding.recyclerViewMinute.smoothScrollToPosition(minutePosition)
552 | }
553 | }, UPDATE_PRE_SELECTED_START_TIME)
554 | } catch (ignored: IllegalArgumentException) {
555 | }
556 | }
557 |
558 | private fun useLiveDataAsCallback() {
559 | activity?.let { _ ->
560 | val viewModel: SnapTimePickerViewModel =
561 | ViewModelProvider(this).get(SnapTimePickerViewModel::class.java)
562 | this.listener = object : Listener {
563 | override fun onTimePicked(hour: Int, minute: Int) {
564 | viewModel.onTimePicked(hour, minute)
565 | }
566 | }
567 | }
568 | }
569 |
570 | private fun onConfirmClick() {
571 | var hour = -1
572 | var minute = -1
573 | val minuteSnappedView = minuteSnapHelper.findSnapView(minuteLayoutManager)
574 | minuteSnappedView?.let { view ->
575 | minute = minuteAdapter.getValueByPosition(minuteLayoutManager.getPosition(view))
576 | }
577 | val hourSnappedView = hourSnapHelper.findSnapView(hourLayoutManager)
578 | hourSnappedView?.let { view ->
579 | hour = hourAdapter.getValueByPosition(hourLayoutManager.getPosition(view))
580 | }
581 | listener?.onTimePicked(hour, minute)
582 | targetFragment?.onActivityResult(targetRequestCode, Activity.RESULT_OK, Intent().apply {
583 | putExtra(EXTRA_SELECTED_HOUR, hour)
584 | putExtra(EXTRA_SELECTED_MINUTE, minute)
585 | })
586 | dismiss()
587 | }
588 |
589 | private fun onCancelClick() {
590 | targetFragment?.onActivityResult(targetRequestCode, Activity.RESULT_CANCELED, null)
591 | dismiss()
592 | }
593 |
594 | private fun isEarlierSelectableTime(): Boolean {
595 | val startHour = selectableTimeRange?.start?.hour ?: -1
596 | val startMinute = selectableTimeRange?.start?.minute ?: -1
597 | val endHour = selectableTimeRange?.end?.hour ?: -1
598 | val endMinute = selectableTimeRange?.end?.minute ?: -1
599 | return startHour != -1 && startMinute != -1 &&
600 | endHour != -1 && endMinute != -1 &&
601 | (startHour < endHour || (startHour == endHour && startMinute < endMinute))
602 | }
603 |
604 | private fun isLaterSelectableTime(): Boolean {
605 | val startHour = selectableTimeRange?.start?.hour ?: -1
606 | val startMinute = selectableTimeRange?.start?.minute ?: -1
607 | val endHour = selectableTimeRange?.end?.hour ?: -1
608 | val endMinute = selectableTimeRange?.end?.minute ?: -1
609 | return startHour != -1 && startMinute != -1 &&
610 | endHour != -1 && endMinute != -1 &&
611 | (startHour > endHour || (startHour == endHour && startMinute > endMinute))
612 | }
613 |
614 | interface Listener {
615 | fun onTimePicked(hour: Int, minute: Int)
616 | }
617 |
618 | class Builder {
619 | private var selectableTimeRange: TimeRange? = null
620 | private var preselectedTime: TimeValue? = null
621 | private var isUseViewModel: Boolean = false
622 | private var title: Int = -1
623 | private var prefix: Int = -1
624 | private var suffix: Int = -1
625 | private var titleColor: Int = -1
626 | private var themeColor: Int = -1
627 | private var negativeButtonText: Int = -1
628 | private var positiveButtonText: Int = -1
629 | private var negativeButtonColor: Int = -1
630 | private var positiveButtonColor: Int = -1
631 | private var buttonTextAllCaps: Boolean = true
632 | private var timeInterval: Int = 1
633 |
634 | fun setPreselectedTime(time: TimeValue): Builder = this.apply {
635 | preselectedTime = time
636 | }
637 |
638 | fun setSelectableTimeRange(timeRange: TimeRange): Builder = this.apply {
639 | selectableTimeRange = timeRange
640 | }
641 |
642 | fun setTitle(@StringRes titleResId: Int): Builder = this.apply {
643 | title = titleResId
644 | }
645 |
646 | fun setPrefix(@StringRes prefixResId: Int): Builder = this.apply {
647 | prefix = prefixResId
648 | }
649 |
650 | fun setSuffix(@StringRes suffixResId: Int): Builder = this.apply {
651 | suffix = suffixResId
652 | }
653 |
654 | fun setTitleColor(@ColorRes colorResId: Int): Builder = this.apply {
655 | titleColor = colorResId
656 | }
657 |
658 | fun setThemeColor(@ColorRes colorResId: Int): Builder = this.apply {
659 | themeColor = colorResId
660 | }
661 |
662 | fun setNegativeButtonText(@StringRes negativeButtonTextId: Int): Builder = this.apply {
663 | negativeButtonText = negativeButtonTextId
664 | }
665 |
666 | fun setPositiveButtonText(@StringRes positiveButtonTextId: Int): Builder = this.apply {
667 | positiveButtonText = positiveButtonTextId
668 | }
669 |
670 | fun setNegativeButtonColor(@ColorRes colorResId: Int): Builder = this.apply {
671 | negativeButtonColor = colorResId
672 | }
673 |
674 | fun setPositiveButtonColor(@ColorRes colorResId: Int): Builder = this.apply {
675 | positiveButtonColor = colorResId
676 | }
677 |
678 | fun setButtonTextAllCaps(isAllCaps: Boolean) {
679 | buttonTextAllCaps = isAllCaps
680 | }
681 |
682 | fun setTimeInterval(interval: Int): Builder = this.apply {
683 | timeInterval = interval
684 | }
685 |
686 | fun useViewModel(): Builder = this.apply {
687 | isUseViewModel = true
688 | }
689 |
690 | fun build(): SnapTimePickerDialog =
691 | newInstance(
692 | selectableTimeRange,
693 | preselectedTime,
694 | isUseViewModel,
695 | title,
696 | prefix,
697 | suffix,
698 | titleColor,
699 | themeColor,
700 | negativeButtonText,
701 | positiveButtonText,
702 | negativeButtonColor,
703 | positiveButtonColor,
704 | buttonTextAllCaps,
705 | timeInterval
706 | )
707 | }
708 | }
709 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/java/com/akexorcist/snaptimepicker/TimeNumberViewHolder.kt:
--------------------------------------------------------------------------------
1 | package com.akexorcist.snaptimepicker
2 |
3 | import androidx.recyclerview.widget.RecyclerView
4 | import com.akexorcist.snaptimepicker.databinding.LayoutSnapTimePickerNumberItemBinding
5 |
6 | class TimeNumberViewHolder(
7 | private val binding: LayoutSnapTimePickerNumberItemBinding
8 | ) : RecyclerView.ViewHolder(binding.root) {
9 | fun setNumber(number: String?) {
10 | binding.textViewNumber.text = number ?: "-"
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/java/com/akexorcist/snaptimepicker/TimePickerAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.akexorcist.snaptimepicker
2 |
3 | import android.view.LayoutInflater
4 | import android.view.ViewGroup
5 | import androidx.recyclerview.widget.RecyclerView
6 | import com.akexorcist.snaptimepicker.databinding.LayoutSnapTimePickerNumberItemBinding
7 |
8 | class TimePickerAdapter : RecyclerView.Adapter() {
9 | private var itemList: List? = null
10 |
11 | override fun onCreateViewHolder(parent: ViewGroup, type: Int): TimeNumberViewHolder =
12 | TimeNumberViewHolder(
13 | LayoutSnapTimePickerNumberItemBinding.inflate(
14 | LayoutInflater.from(
15 | parent.context
16 | ), parent, false
17 | )
18 | )
19 |
20 | override fun getItemCount(): Int = itemList?.size ?: 0
21 |
22 | override fun onBindViewHolder(holder: TimeNumberViewHolder, position: Int) {
23 | val item = itemList?.get(position)
24 | holder.setNumber(item?.toString()?.padStart(2, '0'))
25 | }
26 |
27 | fun setItemList(itemList: List?) {
28 | this.itemList = itemList
29 | notifyDataSetChanged()
30 | }
31 |
32 | fun getPositionByValue(value: Int): Int {
33 | itemList?.forEachIndexed { index, item ->
34 | if (value == item) {
35 | return index
36 | }
37 | }
38 | return -1
39 | }
40 |
41 | fun getValueByPosition(position: Int): Int {
42 | itemList?.forEachIndexed { index, item ->
43 | if (position == index) {
44 | return item
45 | }
46 | }
47 | return -1
48 | }
49 | }
--------------------------------------------------------------------------------
/snap-time-picker/src/main/java/com/akexorcist/snaptimepicker/TimeRange.kt:
--------------------------------------------------------------------------------
1 | package com.akexorcist.snaptimepicker
2 |
3 | import android.os.Parcelable
4 | import kotlinx.parcelize.Parcelize
5 |
6 | @Parcelize
7 | data class TimeRange(
8 | var start: TimeValue?,
9 | var end: TimeValue?
10 | ) : Parcelable
11 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/java/com/akexorcist/snaptimepicker/TimeValue.kt:
--------------------------------------------------------------------------------
1 | package com.akexorcist.snaptimepicker
2 |
3 | import android.os.Parcelable
4 | import kotlinx.parcelize.Parcelize
5 |
6 | @Parcelize
7 | data class TimeValue(
8 | var hour: Int,
9 | var minute: Int
10 | ) : Parcelable
--------------------------------------------------------------------------------
/snap-time-picker/src/main/java/com/akexorcist/snaptimepicker/extension/SnapTimePickerUtil.kt:
--------------------------------------------------------------------------------
1 | package com.akexorcist.snaptimepicker.extension
2 |
3 | import androidx.fragment.app.Fragment
4 | import androidx.fragment.app.FragmentActivity
5 | import androidx.lifecycle.ViewModelProvider
6 |
7 | @Suppress("unused")
8 | object SnapTimePickerUtil {
9 | fun observe(activity: FragmentActivity, onPickedEvent: (hour: Int, minute: Int) -> Unit): Unit =
10 | ViewModelProvider(activity)
11 | .get(SnapTimePickerViewModel::class.java)
12 | .timePickedEvent
13 | .observe(activity, { event: TimePickedEvent ->
14 | onPickedEvent(event.hour, event.minute)
15 | })
16 |
17 | fun observe(fragment: Fragment, onPickedEvent: (hour: Int, minute: Int) -> Unit) =
18 | ViewModelProvider(fragment)
19 | .get(SnapTimePickerViewModel::class.java)
20 | .timePickedEvent
21 | .observe(fragment, { event: TimePickedEvent ->
22 | onPickedEvent(event.hour, event.minute)
23 | })
24 | }
25 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/java/com/akexorcist/snaptimepicker/extension/SnapTimePickerViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.akexorcist.snaptimepicker.extension
2 |
3 | import androidx.lifecycle.ViewModel
4 |
5 | class SnapTimePickerViewModel : ViewModel() {
6 | val timePickedEvent =
7 | TimePickedLiveData()
8 |
9 | fun onTimePicked(hour: Int, minute: Int) {
10 | timePickedEvent.value = TimePickedEvent(hour, minute)
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/java/com/akexorcist/snaptimepicker/extension/TimePickedEvent.kt:
--------------------------------------------------------------------------------
1 | package com.akexorcist.snaptimepicker.extension
2 |
3 | import android.os.Parcel
4 | import android.os.Parcelable
5 |
6 | data class TimePickedEvent(val hour: Int, val minute: Int) : Parcelable {
7 | constructor(parcel: Parcel) : this(
8 | parcel.readInt(),
9 | parcel.readInt()
10 | )
11 |
12 | override fun writeToParcel(parcel: Parcel, flags: Int) {
13 | parcel.writeInt(hour)
14 | parcel.writeInt(minute)
15 | }
16 |
17 | override fun describeContents(): Int {
18 | return 0
19 | }
20 |
21 | companion object CREATOR : Parcelable.Creator {
22 | override fun createFromParcel(parcel: Parcel): TimePickedEvent {
23 | return TimePickedEvent(parcel)
24 | }
25 |
26 | override fun newArray(size: Int): Array {
27 | return arrayOfNulls(size)
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/java/com/akexorcist/snaptimepicker/extension/TimePickedLiveData.kt:
--------------------------------------------------------------------------------
1 | package com.akexorcist.snaptimepicker.extension
2 |
3 | import android.util.Log
4 | import androidx.annotation.MainThread
5 | import androidx.lifecycle.LifecycleOwner
6 | import androidx.lifecycle.MutableLiveData
7 | import androidx.lifecycle.Observer
8 | import java.util.concurrent.atomic.AtomicBoolean
9 |
10 | class TimePickedLiveData : MutableLiveData() {
11 | private val mPending = AtomicBoolean(false)
12 |
13 | companion object {
14 | private const val TAG = "TimePickedLiveData"
15 | }
16 |
17 | @MainThread
18 | override fun observe(owner: LifecycleOwner, observer: Observer) {
19 |
20 | if (hasActiveObservers()) {
21 | Log.w(TAG, "Multiple observers registered but only one will be notified of changes.")
22 | }
23 |
24 | // Observe the internal MutableLiveData
25 | super.observe(owner, { value ->
26 | if (mPending.compareAndSet(true, false)) {
27 | observer.onChanged(value)
28 | }
29 | })
30 | }
31 |
32 | @MainThread
33 | override fun setValue(value: T?) {
34 | mPending.set(true)
35 | super.setValue(value)
36 | }
37 |
38 | @Suppress("unused")
39 | @MainThread
40 | fun call() {
41 | value = null
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/res/drawable-v21/snap_time_picker_selector_button_translucent_black_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | -
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/res/drawable/snap_time_picker_selector_button_translucent_black_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
7 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/res/drawable/snap_time_picker_shadow_bottom_translucent_white.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/res/drawable/snap_time_picker_shadow_top_translucent_white.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/res/drawable/snap_time_picker_shape_background_white.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/res/drawable/snap_time_picker_shape_button_disable_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
10 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/res/drawable/snap_time_picker_shape_button_translucent_black_round_pressed.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
10 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/res/drawable/snap_time_picker_shape_button_transparent_round_normal.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
10 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/res/layout/layout_snap_time_picker_dialog.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
14 |
24 |
25 |
36 |
37 |
46 |
47 |
56 |
57 |
58 |
67 |
68 |
74 |
75 |
81 |
82 |
93 |
94 |
104 |
105 |
115 |
116 |
122 |
123 |
130 |
131 |
138 |
139 |
147 |
148 |
159 |
160 |
161 |
162 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/res/layout/layout_snap_time_picker_number_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
23 |
24 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #00ffffff
4 | #FFFFFF
5 | #333333
6 | #0c000000
7 | #008577
8 | #D81B60
9 | #c2c2c2
10 | #ebebeb
11 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 300dp
4 | 300dp
5 | 64dp
6 | 8dp
7 | 16dp
8 | 4dp
9 | 2dp
10 | 1dp
11 | 60dp
12 | 80dp
13 | 50dp
14 | 36dp
15 | 4dp
16 | 1dp
17 |
18 | 12sp
19 | 14sp
20 | 16sp
21 | 18sp
22 | 22sp
23 | 28sp
24 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | @android:string/cancel
3 | @android:string/ok
4 | :
5 |
6 |
--------------------------------------------------------------------------------
/snap-time-picker/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
10 |
11 |
15 |
16 |
26 |
27 |
32 |
--------------------------------------------------------------------------------