├── .gitignore ├── LICENSE.txt ├── README.md ├── build.gradle ├── gradle.properties ├── gradle ├── gradle-mvn-push.gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── jetpack-bindings-arguments ├── build.gradle ├── gradle.properties └── src │ ├── main │ ├── AndroidManifest.xml │ └── kotlin │ │ └── com │ │ └── github │ │ └── vmironov │ │ └── jetpack │ │ └── arguments │ │ ├── ArgumentsBindings.kt │ │ └── SupportUtils.kt │ └── test │ └── kotlin │ └── com │ └── github │ └── vmironov │ └── github │ └── jetpack │ └── arguments │ └── ArgumentBindingsTest.kt ├── jetpack-bindings-preferences ├── build.gradle ├── gradle.properties └── src │ └── main │ ├── AndroidManifest.xml │ └── kotlin │ └── com │ └── github │ └── vmironov │ └── jetpack │ └── preferences │ ├── PreferencesBindings.kt │ └── SupportUtils.kt ├── jetpack-bindings-resources ├── build.gradle ├── gradle.properties └── src │ └── main │ ├── AndroidManifest.xml │ └── kotlin │ └── com │ └── github │ └── vmironov │ └── jetpack │ └── resources │ ├── ResourcesBindings.kt │ └── SupportUtils.kt ├── jetpack-bindings-sample ├── build.gradle └── src │ └── main │ ├── AndroidManifest.xml │ ├── kotlin │ └── com │ │ └── github │ │ └── vmironov │ │ └── jetpack │ │ └── sample │ │ ├── SampleActivity.kt │ │ └── SampleFragment.kt │ └── res │ ├── drawable │ └── ic_done_white_24dp.xml │ ├── layout │ ├── activity_sample.xml │ └── fragment_sample.xml │ ├── menu │ └── menu_sample.xml │ └── values │ ├── colors.xml │ ├── dimens.xml │ ├── strings.xml │ └── themes.xml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .idea 3 | .DS_Store 4 | 5 | local.properties 6 | captures 7 | build 8 | 9 | *.iml 10 | -------------------------------------------------------------------------------- /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 [yyyy] [name of copyright owner] 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. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kotlin Jetpack [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-Kotlin%20Jetpack-green.svg?style=flat)](https://android-arsenal.com/details/1/2588) 2 | A collection of useful extension methods for Android 3 | 4 | * [Arguments Bindings](#arguments-bindings) 5 | * [Preferences Bindings](#preferences-bindings) 6 | * [Resources Bindings](#resources-bindings) 7 | 8 | # Arguments Bindings 9 | ```kotlin 10 | public class ArgumentsFragment : Fragment() { 11 | public companion object { 12 | public fun newInstance(): ArgumentsFragment = ArgumentsFragment().apply { 13 | arguments = Bundle().apply { 14 | putBoolean("extra_boolean", true) 15 | } 16 | } 17 | } 18 | 19 | // Required binding without default value 20 | val booleanOrThrow by bindArgument("extra_boolean") 21 | 22 | // Required binding with default value 23 | val booleanOrDefault by bindArgument("extra_boolean", false) 24 | 25 | // Optional binding 26 | val booleanOrNull by bindOptionalArgument("extra_boolean") 27 | } 28 | ``` 29 | These methods can be used with `Activity`, `Fragment`, and support library `Fragment` subclasses. You can also implement `ArgumentsAware` interface to provide a custom arguments source. Full list of supported bindings: 30 | - `bindArgument` / `bindOptionalArgument` 31 | - `bindArgument` / `bindOptionalArgument` 32 | - `bindArgument` / `bindOptionalArgument` 33 | - `bindArgument` / `bindOptionalArgument` 34 | - `bindArgument` / `bindOptionalArgument` 35 | - `bindArgument` / `bindOptionalArgument` 36 | - `bindArgument` / `bindOptionalArgument` 37 | - `bindArgument` / `bindOptionalArgument` 38 | - `bindArgument` / `bindOptionalArgument` 39 | - `bindArgument` / `bindOptionalArgument` 40 | 41 | Every `bindXXXArgument` returns a `ReadWriteProperty` so they can be used with `var`'s as well. In this case you don't have to deal with `Bundle` at all. No explicit `Bundle` creation, no silly `EXTRA_XXX` constants, no annoying `Bundle.putXXX` and `Bundle.getXXX` calls. Everything just works: 42 | ```kotlin 43 | public class UserProfileFragment : Fragment() { 44 | public companion object { 45 | public fun newInstance(): UserProfileFragment = UserProfileFragment().apply { 46 | this.firstName = "Vladimir" 47 | this.lastName = "Mironov" 48 | } 49 | } 50 | 51 | // extra name is automatically inferred from property name ("firstName" in this case) 52 | var firstName by bindArgument() 53 | 54 | // you can also provide a default value using "default" named argument 55 | var lastName by bindArgument(default = "") 56 | } 57 | ``` 58 | 59 | Gradle dependency: 60 | ```gradle 61 | compile "com.github.vmironov.jetpack:jetpack-bindings-arguments:0.14.2" 62 | ``` 63 | 64 | # Preferences Bindings 65 | ```kotlin 66 | public class PreferencesFragment : Fragment() { 67 | // Boolean preference 68 | var boolean by bindPreference("boolean", false) 69 | 70 | // Float preference 71 | var float by bindPreference("float", 0.0f) 72 | 73 | // Integer preference 74 | var integer by bindPreference("integer", 1) 75 | 76 | // Long preference 77 | var long by bindPreference("long", 1L) 78 | 79 | // String preference 80 | var string by bindPreference("string", "default") 81 | } 82 | ``` 83 | 84 | These methods can be used with `Context`, `Fragment`, support library `Fragment`, `View`, and `ViewHolder` subclasses. The example above uses a default `SharedPreferences` instance. You can always provide a custom one by implementing `PreferencesAware` interface: 85 | ```kotlin 86 | public class PreferencesFragment : Fragment() { 87 | val preferences = PreferencesAware { 88 | activity.getSharedPreferences("CustomSharedPreferences", Context.MODE_PRIVATE) 89 | } 90 | 91 | var boolean by preferences.bindPreference("boolean", false) 92 | var float by preferences.bindPreference("float", 0.0f) 93 | var integer by preferences.bindPreference("integer", 1) 94 | var long by preferences.bindPreference("long", 1L) 95 | var string by preferences.bindPreference("string", "default") 96 | 97 | // Optional preferences are supported as well 98 | var optionalLong by preferences.bindOptionalPreference() 99 | var optionalString by preferences.bindOptionalPreference() 100 | } 101 | ``` 102 | Although only `Boolean`, `Float`, `Int`, `Long` and `String` preferences are supported by default, the library can be easily extented to support custom type of preference. `Adapter` interface can be implemented in order to convert any type to a supported one. Here is an example how to imlement `json`-based preferences using `Gson`: 103 | ```kotlin 104 | public inline fun Any.bindGsonPreference(default: E, key: String? = null): ReadWriteProperty { 105 | return bindPreference(default, GsonPreferenceAdapter(E::class.java), key) 106 | } 107 | 108 | public inline fun Any.bindGsonPreference(noinline default: () -> E, key: String? = null): ReadWriteProperty { 109 | return bindPreference(default, GsonPreferenceAdapter(E::class.java), key) 110 | } 111 | 112 | public class GsonPreferenceAdapter(val clazz: Class, val gson: Gson = GsonPreferenceAdapter.GSON) : Adapter { 113 | override fun type(): Class = String::class.java 114 | override fun fromPreference(preference: String): T = gson.fromJson(preference, clazz) 115 | override fun toPreference(value: T): String = gson.toJson(value) 116 | 117 | public companion object { 118 | public val GSON = Gson() 119 | } 120 | } 121 | 122 | ``` 123 | Usage: 124 | ```kotlin 125 | public data class Profile(val firstName: String? = null, val lastName: String? = null) 126 | 127 | public class ProfileManager(val context: Context) { 128 | public var profile by bindGsonPreference(Profile()) 129 | } 130 | ``` 131 | 132 | Gradle dependency: 133 | ```gradle 134 | compile "com.github.vmironov.jetpack:jetpack-bindings-preferences:0.14.2" 135 | ``` 136 | 137 | # Resources Bindings 138 | ```kotlin 139 | public class ResourcesFragment : Fragment() { 140 | // Boolean resource binding 141 | val boolean by bindResource(R.boolean.boolean_resource) 142 | 143 | // Color resource binding 144 | val color by bindResource(R.color.color_resource) 145 | 146 | // Drawable resource binding #1 147 | val bitmap by bindResource(R.drawable.drawable_bitmap) 148 | 149 | // Drawable resource binding #2 150 | val vector by bindResource(R.drawable.drawable_vector) 151 | 152 | // Dimension resource binding 153 | val dimension by bindResource(R.dimen.dimen_resource) 154 | 155 | // String resource binding 156 | val string by bindResource(R.string.string_resource) 157 | } 158 | ``` 159 | These methods can be used with `Activity`, `Context`, `Fragment`, support library `Fragment`, `View`, and `ViewHolder` subclasses. You can also implement `ResourcesAware` interface to provide a custom resources source. Full list of supported bindings: 160 | - `bindResource(R.boolean.boolean_resource)` 161 | - `bindResource(R.integer.integer_resource)` 162 | - `bindResource(R.color.color_resource)` 163 | - `bindResource(R.color.color_resource)` 164 | - `bindResource(R.drawable.drawable_resource)` 165 | - `bindResource(R.dimen.dimen_resource)` 166 | - `bindResource(R.dimen.dimen_resource)` 167 | - `bindResource(R.string.string_resource)` 168 | - `bindResource(R.string.string_resource)` 169 | - `bindResource(R.array.array_resource)` 170 | - `bindResource>(R.array.array_resource)` 171 | - `bindResource>(R.array.array_resource)` 172 | 173 | Gradle dependency: 174 | ```gradle 175 | compile "com.github.vmironov.jetpack:jetpack-bindings-resources:0.14.2" 176 | ``` 177 | 178 | # License 179 | 180 | Copyright 2015 Vladimir Mironov 181 | 182 | Licensed under the Apache License, Version 2.0 (the "License"); 183 | you may not use this file except in compliance with the License. 184 | You may obtain a copy of the License at 185 | 186 | http://www.apache.org/licenses/LICENSE-2.0 187 | 188 | Unless required by applicable law or agreed to in writing, software 189 | distributed under the License is distributed on an "AS IS" BASIS, 190 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 191 | See the License for the specific language governing permissions and 192 | limitations under the License. 193 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext.kotlinVersion = "1.0.0" 3 | 4 | repositories { 5 | jcenter() 6 | } 7 | 8 | dependencies { 9 | classpath "com.android.tools.build:gradle:1.5.0" 10 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" 11 | } 12 | } 13 | 14 | allprojects { 15 | buildscript { 16 | repositories { 17 | jcenter() 18 | } 19 | } 20 | 21 | repositories { 22 | jcenter() 23 | } 24 | } 25 | 26 | ext { 27 | projectCompileSdkVersion = 23 28 | projectBuildToolsVersion = "23.0.1" 29 | 30 | projectMinSdkVersion = 14 31 | projectTargetSdkVersion = 23 32 | 33 | supportVersion = "23.1.1" 34 | } 35 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | GROUP=com.github.vmironov.jetpack 2 | VERSION_NAME=0.14.3-SNAPSHOT 3 | 4 | POM_DESCRIPTION=A collection of useful extension methods for Android. 5 | 6 | POM_URL=https://github.com/nsk-mironov/kotlin-jetpack 7 | POM_SCM_URL=https://github.com/nsk-mironov/kotlin-jetpack.git 8 | POM_SCM_CONNECTION=scm:git:git://github.com/nsk-mironov/kotlin-jetpack.git 9 | POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/nsk-mironov/kotlin-jetpack.git 10 | 11 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 12 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 13 | POM_LICENCE_DIST=repo 14 | 15 | POM_DEVELOPER_ID=nsk-mironov 16 | POM_DEVELOPER_NAME=Vladimir Mironov 17 | -------------------------------------------------------------------------------- /gradle/gradle-mvn-push.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Chris Banes 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'maven' 18 | apply plugin: 'signing' 19 | 20 | version = VERSION_NAME 21 | group = GROUP 22 | 23 | def isReleaseBuild() { 24 | return VERSION_NAME.contains("SNAPSHOT") == false 25 | } 26 | 27 | def getReleaseRepositoryUrl() { 28 | return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL 29 | : "https://oss.sonatype.org/service/local/staging/deploy/maven2/" 30 | } 31 | 32 | def getSnapshotRepositoryUrl() { 33 | return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL 34 | : "https://oss.sonatype.org/content/repositories/snapshots/" 35 | } 36 | 37 | def getRepositoryUsername() { 38 | return hasProperty('SONATYPE_NEXUS_USERNAME') ? SONATYPE_NEXUS_USERNAME : "" 39 | } 40 | 41 | def getRepositoryPassword() { 42 | return hasProperty('SONATYPE_NEXUS_PASSWORD') ? SONATYPE_NEXUS_PASSWORD : "" 43 | } 44 | 45 | afterEvaluate { project -> 46 | uploadArchives { 47 | repositories { 48 | mavenDeployer { 49 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 50 | 51 | pom.groupId = GROUP 52 | pom.artifactId = POM_ARTIFACT_ID 53 | pom.version = VERSION_NAME 54 | 55 | repository(url: getReleaseRepositoryUrl()) { 56 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) 57 | } 58 | snapshotRepository(url: getSnapshotRepositoryUrl()) { 59 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) 60 | } 61 | 62 | pom.project { 63 | name POM_NAME 64 | packaging POM_PACKAGING 65 | description POM_DESCRIPTION 66 | url POM_URL 67 | 68 | scm { 69 | url POM_SCM_URL 70 | connection POM_SCM_CONNECTION 71 | developerConnection POM_SCM_DEV_CONNECTION 72 | } 73 | 74 | licenses { 75 | license { 76 | name POM_LICENCE_NAME 77 | url POM_LICENCE_URL 78 | distribution POM_LICENCE_DIST 79 | } 80 | } 81 | 82 | developers { 83 | developer { 84 | id POM_DEVELOPER_ID 85 | name POM_DEVELOPER_NAME 86 | } 87 | } 88 | } 89 | } 90 | } 91 | } 92 | 93 | signing { 94 | required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") } 95 | sign configurations.archives 96 | } 97 | 98 | if (project.getPlugins().hasPlugin('com.android.application') || 99 | project.getPlugins().hasPlugin('com.android.library')) { 100 | task install(type: Upload, dependsOn: assemble) { 101 | repositories.mavenInstaller { 102 | configuration = configurations.archives 103 | 104 | pom.groupId = GROUP 105 | pom.artifactId = POM_ARTIFACT_ID 106 | pom.version = VERSION_NAME 107 | 108 | pom.project { 109 | name POM_NAME 110 | packaging POM_PACKAGING 111 | description POM_DESCRIPTION 112 | url POM_URL 113 | 114 | scm { 115 | url POM_SCM_URL 116 | connection POM_SCM_CONNECTION 117 | developerConnection POM_SCM_DEV_CONNECTION 118 | } 119 | 120 | licenses { 121 | license { 122 | name POM_LICENCE_NAME 123 | url POM_LICENCE_URL 124 | distribution POM_LICENCE_DIST 125 | } 126 | } 127 | 128 | developers { 129 | developer { 130 | id POM_DEVELOPER_ID 131 | name POM_DEVELOPER_NAME 132 | } 133 | } 134 | } 135 | } 136 | } 137 | 138 | task androidJavadocs(type: Javadoc) { 139 | source = android.sourceSets.main.java.source 140 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 141 | failOnError = false 142 | } 143 | 144 | task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { 145 | classifier = 'javadoc' 146 | from androidJavadocs.destinationDir 147 | } 148 | 149 | task androidSourcesJar(type: Jar) { 150 | classifier = 'sources' 151 | from android.sourceSets.main.java.source 152 | } 153 | } else { 154 | install { 155 | repositories.mavenInstaller { 156 | pom.groupId = GROUP 157 | pom.artifactId = POM_ARTIFACT_ID 158 | pom.version = VERSION_NAME 159 | 160 | pom.project { 161 | name POM_NAME 162 | packaging POM_PACKAGING 163 | description POM_DESCRIPTION 164 | url POM_URL 165 | 166 | scm { 167 | url POM_SCM_URL 168 | connection POM_SCM_CONNECTION 169 | developerConnection POM_SCM_DEV_CONNECTION 170 | } 171 | 172 | licenses { 173 | license { 174 | name POM_LICENCE_NAME 175 | url POM_LICENCE_URL 176 | distribution POM_LICENCE_DIST 177 | } 178 | } 179 | 180 | developers { 181 | developer { 182 | id POM_DEVELOPER_ID 183 | name POM_DEVELOPER_NAME 184 | } 185 | } 186 | } 187 | } 188 | } 189 | 190 | task sourcesJar(type: Jar, dependsOn:classes) { 191 | classifier = 'sources' 192 | from sourceSets.main.allSource 193 | } 194 | 195 | task javadocJar(type: Jar, dependsOn:javadoc) { 196 | classifier = 'javadoc' 197 | from javadoc.destinationDir 198 | } 199 | } 200 | 201 | if (JavaVersion.current().isJava8Compatible()) { 202 | allprojects { 203 | tasks.withType(Javadoc) { 204 | options.addStringOption('Xdoclint:none', '-quiet') 205 | } 206 | } 207 | } 208 | 209 | artifacts { 210 | if (project.getPlugins().hasPlugin('com.android.application') || 211 | project.getPlugins().hasPlugin('com.android.library')) { 212 | archives androidSourcesJar 213 | archives androidJavadocsJar 214 | } else { 215 | archives sourcesJar 216 | archives javadocJar 217 | } 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nsk-mironov/kotlin-jetpack/cad048de889991ffe90a8f11610823124812beb2/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Oct 26 00:19:47 MSK 2015 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-2.8-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >&- 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >&- 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /jetpack-bindings-arguments/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "com.android.library" 2 | apply plugin: "kotlin-android" 3 | 4 | android { 5 | compileSdkVersion projectCompileSdkVersion 6 | buildToolsVersion projectBuildToolsVersion 7 | 8 | defaultConfig { 9 | targetSdkVersion projectTargetSdkVersion 10 | minSdkVersion projectMinSdkVersion 11 | } 12 | 13 | sourceSets { 14 | main.java.srcDirs += 'src/main/kotlin' 15 | main.java.srcDirs += 'src/main/generated' 16 | 17 | androidTest.java.srcDirs += 'src/test/kotlin' 18 | } 19 | } 20 | 21 | dependencies { 22 | provided "com.android.support:support-v4:$supportVersion" 23 | provided "com.android.support:recyclerview-v7:$supportVersion" 24 | 25 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" 26 | } 27 | 28 | apply from: rootProject.file('gradle/gradle-mvn-push.gradle') 29 | -------------------------------------------------------------------------------- /jetpack-bindings-arguments/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_ARTIFACT_ID=jetpack-bindings-arguments 2 | POM_NAME=Jetpack Arguments Bindings 3 | POM_PACKAGING=aar 4 | -------------------------------------------------------------------------------- /jetpack-bindings-arguments/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /jetpack-bindings-arguments/src/main/kotlin/com/github/vmironov/jetpack/arguments/ArgumentsBindings.kt: -------------------------------------------------------------------------------- 1 | package com.github.vmironov.jetpack.arguments 2 | 3 | import android.app.Activity 4 | import android.app.Fragment 5 | import android.content.Intent 6 | import android.os.Bundle 7 | import android.os.Parcelable 8 | import java.io.Serializable 9 | import kotlin.properties.ReadWriteProperty 10 | import kotlin.reflect.KProperty 11 | 12 | interface ArgumentsAware { 13 | var arguments: Bundle? 14 | } 15 | 16 | inline fun Any.bindArgument(name: String? = null, default: T? = null, adapter: Adapter? = null): ReadWriteProperty { 17 | return ArgumentsVar(T::class.java, adapter, this, name, default) 18 | } 19 | 20 | inline fun Any.bindOptionalArgument(name: String? = null, default: T? = null, adapter: Adapter? = null): ReadWriteProperty { 21 | return OptionalArgumentsVar(T::class.java, adapter, this, name, default) 22 | } 23 | 24 | @Suppress("BASE_WITH_NULLABLE_UPPER_BOUND") class ArgumentsVar( 25 | private val clazz: Class, 26 | private val adapter: Adapter?, 27 | private val source: Any, 28 | private val name: String?, 29 | private val default: V? 30 | ) : ReadWriteProperty { 31 | private val delegate = ArgumentsVarDelegate(adapter ?: createTypeAdapterFor(clazz), source, name, default) 32 | 33 | override operator fun getValue(thisRef: T, property: KProperty<*>): V { 34 | return delegate.getValue(thisRef, property) ?: throw IllegalArgumentException("Key ${name ?: property.name} is missed") 35 | } 36 | 37 | override operator fun setValue(thisRef: T, property: KProperty<*>, value: V) { 38 | delegate.setValue(thisRef, property, value) 39 | } 40 | } 41 | 42 | @Suppress("BASE_WITH_NULLABLE_UPPER_BOUND") class OptionalArgumentsVar( 43 | private val clazz: Class, 44 | private val adapter: Adapter?, 45 | private val source: Any, 46 | private val name: String?, 47 | private val default: V? 48 | ) : ReadWriteProperty { 49 | private val delegate = ArgumentsVarDelegate(adapter ?: createTypeAdapterFor(clazz), source, name, default) 50 | 51 | override operator fun getValue(thisRef: T, property: KProperty<*>): V? { 52 | return delegate.getValue(thisRef, property) 53 | } 54 | 55 | override operator fun setValue(thisRef: T, property: KProperty<*>, value: V?) { 56 | delegate.setValue(thisRef, property, value) 57 | } 58 | } 59 | 60 | @Suppress("BASE_WITH_NULLABLE_UPPER_BOUND") 61 | private class ArgumentsVarDelegate( 62 | private val adapter: Adapter, 63 | private val source: Any, 64 | private val name: String?, 65 | private val default: V? 66 | ) : ReadWriteProperty { 67 | 68 | override operator fun getValue(thisRef: T, property: KProperty<*>): V? { 69 | val extra = name ?: property.name 70 | val bundle = getArgumentsFromSource(source) ?: Bundle.EMPTY 71 | 72 | val value = if (bundle.containsKey(extra)) { 73 | adapter[bundle, extra] 74 | } else { 75 | null 76 | } 77 | 78 | @Suppress("UNCHECKED_CAST") 79 | return value ?: default 80 | } 81 | 82 | override operator fun setValue(thisRef: T, property: KProperty<*>, value: V?) { 83 | val bundle = getArgumentsFromSource(source) 84 | val target = bundle ?: Bundle() 85 | val extra = name ?: property.name 86 | 87 | if (bundle == null) { 88 | setArgumentsToSource(source, target) 89 | } 90 | 91 | if (value != null) { 92 | adapter.set(target, extra, value) 93 | } else { 94 | target.remove(extra) 95 | } 96 | } 97 | 98 | private fun getArgumentsFromSource(source: Any): Bundle? { 99 | return when { 100 | source is ArgumentsAware -> source.arguments 101 | SupportHelper.isFragment(source) -> SupportFragmentHelper.getArguments(source) 102 | source is Activity -> source.intent.extras 103 | source is Bundle -> source 104 | source is Intent -> source.extras 105 | source is Fragment -> source.arguments 106 | else -> throw IllegalArgumentException("Unable to get arguments on type ${source.javaClass.simpleName}") 107 | } 108 | } 109 | 110 | private fun setArgumentsToSource(source: Any, bundle: Bundle) { 111 | when { 112 | source is ArgumentsAware -> source.arguments = bundle 113 | SupportHelper.isFragment(source) -> SupportFragmentHelper.setArguments(source, bundle) 114 | source is Activity -> source.intent.replaceExtras(bundle) 115 | source is Bundle -> source.replaceExtras(bundle) 116 | source is Intent -> source.replaceExtras(bundle) 117 | source is Fragment -> source.arguments = bundle 118 | else -> throw IllegalArgumentException("Unable to set arguments on type ${source.javaClass.simpleName}") 119 | } 120 | } 121 | } 122 | 123 | private fun Bundle.replaceExtras(extras: Bundle) { 124 | clear() 125 | putAll(extras) 126 | } 127 | 128 | @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST", "CAST_NEVER_SUCCEEDS") 129 | private fun createTypeAdapterFor(clazz: Class): Adapter { 130 | fun typed(desiredClass: Class<*>): Boolean { 131 | return desiredClass.isAssignableFrom(clazz) 132 | } 133 | 134 | return when { 135 | typed(kotlin.Boolean::class.java) -> BooleanAdapter 136 | typed(kotlin.Double::class.java) -> DoubleAdapter 137 | typed(kotlin.Int::class.java) -> IntAdapter 138 | typed(kotlin.Long::class.java) -> LongAdapter 139 | typed(kotlin.String::class.java) -> StringAdapter 140 | typed(kotlin.CharSequence::class.java) -> CharSequenceAdapter 141 | typed(kotlin.Float::class.java) -> FloatAdapter 142 | typed(kotlin.Enum::class.java) -> EnumAdapter(clazz as Class>) 143 | 144 | typed(java.lang.Boolean::class.java) -> BooleanAdapter 145 | typed(java.lang.Double::class.java) -> DoubleAdapter 146 | typed(java.lang.Integer::class.java) -> IntAdapter 147 | typed(java.lang.Long::class.java) -> LongAdapter 148 | typed(java.lang.String::class.java) -> StringAdapter 149 | typed(java.lang.CharSequence::class.java) -> CharSequenceAdapter 150 | typed(java.lang.Float::class.java) -> FloatAdapter 151 | typed(java.lang.Enum::class.java) -> EnumAdapter(clazz as Class>) 152 | 153 | typed(Parcelable::class.java) -> ParcelableAdapter 154 | typed(Serializable::class.java) -> SerializableAdapter 155 | 156 | else -> throw UnsupportedOperationException("Unable to create a type Adapter for \"${clazz.name}\"") 157 | } as Adapter 158 | } 159 | 160 | interface Adapter { 161 | operator fun set(bundle: Bundle, name: String, value: T): Unit 162 | operator fun get(bundle: Bundle, name: String): T 163 | } 164 | 165 | private object BooleanAdapter : Adapter { 166 | override operator fun set(bundle: Bundle, name: String, value: Boolean) { 167 | bundle.putBoolean(name, value) 168 | } 169 | 170 | override operator fun get(bundle: Bundle, name: String): Boolean { 171 | return bundle.getBoolean(name) 172 | } 173 | } 174 | 175 | private object DoubleAdapter : Adapter { 176 | override operator fun set(bundle: Bundle, name: String, value: Double) { 177 | bundle.putDouble(name, value) 178 | } 179 | 180 | override operator fun get(bundle: Bundle, name: String): Double { 181 | return bundle.getDouble(name) 182 | } 183 | } 184 | 185 | private object IntAdapter : Adapter { 186 | override operator fun set(bundle: Bundle, name: String, value: Int) { 187 | bundle.putInt(name, value) 188 | } 189 | 190 | override operator fun get(bundle: Bundle, name: String): Int { 191 | return bundle.getInt(name) 192 | } 193 | } 194 | 195 | private object LongAdapter : Adapter { 196 | override operator fun set(bundle: Bundle, name: String, value: Long) { 197 | bundle.putLong(name, value) 198 | } 199 | 200 | override operator fun get(bundle: Bundle, name: String): Long { 201 | return bundle.getLong(name) 202 | } 203 | } 204 | 205 | private object StringAdapter : Adapter { 206 | override operator fun set(bundle: Bundle, name: String, value: String) { 207 | bundle.putString(name, value) 208 | } 209 | 210 | override operator fun get(bundle: Bundle, name: String): String { 211 | return bundle.getString(name) 212 | } 213 | } 214 | 215 | private object CharSequenceAdapter : Adapter { 216 | override operator fun set(bundle: Bundle, name: String, value: CharSequence) { 217 | bundle.putCharSequence(name, value) 218 | } 219 | 220 | override operator fun get(bundle: Bundle, name: String): CharSequence { 221 | return bundle.getCharSequence(name) 222 | } 223 | } 224 | 225 | private object FloatAdapter : Adapter { 226 | override operator fun set(bundle: Bundle, name: String, value: Float) { 227 | bundle.putFloat(name, value) 228 | } 229 | 230 | override operator fun get(bundle: Bundle, name: String): Float { 231 | return bundle.getFloat(name) 232 | } 233 | } 234 | 235 | private class EnumAdapter(val clazz: Class>) : Adapter> { 236 | override operator fun set(bundle: Bundle, name: String, value: Enum<*>) { 237 | bundle.putString(name, value.name) 238 | } 239 | 240 | override operator fun get(bundle: Bundle, name: String): Enum<*> { 241 | return clazz.enumConstants.firstOrNull { 242 | it.name == bundle.getString(name) 243 | } ?: throw IllegalArgumentException("\"$name\" is not a constant in \"${clazz.name}\"") 244 | } 245 | } 246 | 247 | private object ParcelableAdapter : Adapter { 248 | override operator fun set(bundle: Bundle, name: String, value: Parcelable) { 249 | bundle.putParcelable(name, value) 250 | } 251 | 252 | override operator fun get(bundle: Bundle, name: String): Parcelable { 253 | return bundle.getParcelable(name) 254 | } 255 | } 256 | 257 | private object SerializableAdapter : Adapter { 258 | override operator fun set(bundle: Bundle, name: String, value: Serializable) { 259 | bundle.putSerializable(name, value) 260 | } 261 | 262 | override operator fun get(bundle: Bundle, name: String): Serializable { 263 | return bundle.getSerializable(name) 264 | } 265 | } -------------------------------------------------------------------------------- /jetpack-bindings-arguments/src/main/kotlin/com/github/vmironov/jetpack/arguments/SupportUtils.kt: -------------------------------------------------------------------------------- 1 | package com.github.vmironov.jetpack.arguments 2 | 3 | import android.os.Bundle 4 | 5 | internal object SupportHelper { 6 | private val HAS_SUPPORT_FRAGMENTS = try { 7 | Class.forName("android.support.v4.app.Fragment") != null 8 | } catch (exception: Exception) { 9 | false 10 | } 11 | 12 | internal fun isFragment(target: Any): Boolean { 13 | return HAS_SUPPORT_FRAGMENTS && SupportFragmentHelper.isFragment(target) 14 | } 15 | } 16 | 17 | internal object SupportFragmentHelper { 18 | internal fun isFragment(target: Any): Boolean { 19 | return target is android.support.v4.app.Fragment 20 | } 21 | 22 | internal fun getArguments(target: Any): Bundle? { 23 | return (target as android.support.v4.app.Fragment).arguments 24 | } 25 | 26 | internal fun setArguments(target: Any, bundle: Bundle) { 27 | (target as android.support.v4.app.Fragment).arguments = bundle 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /jetpack-bindings-arguments/src/test/kotlin/com/github/vmironov/github/jetpack/arguments/ArgumentBindingsTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.vmironov.github.jetpack.arguments 2 | 3 | import android.app.Fragment 4 | import android.os.Bundle 5 | import android.test.AndroidTestCase 6 | import com.github.vmironov.jetpack.arguments.* 7 | import junit.framework.Assert 8 | 9 | class ArgumentBindingsTest : AndroidTestCase() { 10 | fun testExplicitRequiredBindings() { 11 | class ArgumentsFragment : Fragment() { 12 | var integer by bindArgument(default = 12) 13 | var boolean by bindArgument() 14 | var string by bindArgument() 15 | var long by bindArgument() 16 | var double by bindArgument() 17 | var float by bindArgument() 18 | } 19 | 20 | val fragment = ArgumentsFragment().apply { 21 | integer = 12 22 | boolean = true 23 | string = "rainbow dash" 24 | long = 37L 25 | double = 1.25 26 | float = 2.5f 27 | } 28 | 29 | Assert.assertEquals(12, fragment.integer) 30 | Assert.assertEquals(true, fragment.boolean) 31 | Assert.assertEquals("rainbow dash", fragment.string) 32 | Assert.assertEquals(37L, fragment.long) 33 | Assert.assertEquals(1.25, fragment.double) 34 | Assert.assertEquals(2.5f, fragment.float) 35 | } 36 | 37 | fun testImplicitRequiredBindings() { 38 | class ArgumentsFragment : Fragment() { 39 | val integer by bindArgument() 40 | val boolean by bindArgument() 41 | val string by bindArgument() 42 | val long by bindArgument() 43 | val double by bindArgument() 44 | val float by bindArgument() 45 | } 46 | 47 | val fragment = ArgumentsFragment().apply { 48 | arguments = Bundle().apply { 49 | putInt("integer", 33) 50 | putBoolean("boolean", false) 51 | putString("string", "pinkie pie") 52 | putLong("long", 14L) 53 | putDouble("double", 3.14) 54 | putFloat("float", 2.71f) 55 | } 56 | } 57 | 58 | Assert.assertEquals(33, fragment.integer) 59 | Assert.assertEquals(false, fragment.boolean) 60 | Assert.assertEquals("pinkie pie", fragment.string) 61 | Assert.assertEquals(14L, fragment.long) 62 | Assert.assertEquals(3.14, fragment.double) 63 | Assert.assertEquals(2.71f, fragment.float) 64 | } 65 | 66 | fun testRequiredBindingsWithDefaultsWhenArgumentsMissedWithoutBundle() { 67 | class ArgumentsFragment : Fragment() { 68 | val integer by bindArgument("integer", 4) 69 | val boolean by bindArgument("boolean", true) 70 | val string by bindArgument("string", "flutter shy") 71 | val long by bindArgument("long", 7L) 72 | val double by bindArgument("double", 1.23) 73 | val float by bindArgument("float", 4.56f) 74 | } 75 | 76 | val fragment = ArgumentsFragment().apply { 77 | arguments = null 78 | } 79 | 80 | Assert.assertEquals(4, fragment.integer) 81 | Assert.assertEquals(true, fragment.boolean) 82 | Assert.assertEquals("flutter shy", fragment.string) 83 | Assert.assertEquals(7L, fragment.long) 84 | Assert.assertEquals(1.23, fragment.double) 85 | Assert.assertEquals(4.56f, fragment.float) 86 | } 87 | 88 | fun testRequiredBindingsWithDefaultsWhenArgumentsMissedWithEmptyBundle() { 89 | class ArgumentsFragment : Fragment() { 90 | val integer by bindArgument("integer", 4) 91 | val boolean by bindArgument("boolean", true) 92 | val string by bindArgument("string", "flutter shy") 93 | val long by bindArgument("long", 7L) 94 | val double by bindArgument("double", 1.23) 95 | val float by bindArgument("float", 4.56f) 96 | } 97 | 98 | val fragment = ArgumentsFragment().apply { 99 | arguments = Bundle.EMPTY 100 | } 101 | 102 | Assert.assertEquals(4, fragment.integer) 103 | Assert.assertEquals(true, fragment.boolean) 104 | Assert.assertEquals("flutter shy", fragment.string) 105 | Assert.assertEquals(7L, fragment.long) 106 | Assert.assertEquals(1.23, fragment.double) 107 | Assert.assertEquals(4.56f, fragment.float) 108 | } 109 | 110 | fun testRequiredBindingsWithDefaultsWhenArgumentsSet() { 111 | class ArgumentsFragment : Fragment() { 112 | val integer by bindArgument("integer", 4) 113 | val boolean by bindArgument("boolean", true) 114 | val string by bindArgument("string", "flutter shy") 115 | val long by bindArgument("long", 7L) 116 | val double by bindArgument("double", 1.23) 117 | val float by bindArgument("float", 4.56f) 118 | } 119 | 120 | val fragment = ArgumentsFragment().apply { 121 | arguments = Bundle().apply { 122 | putInt("integer", 33) 123 | putBoolean("boolean", false) 124 | putString("string", "pinkie pie") 125 | putLong("long", 14L) 126 | putDouble("double", 3.14) 127 | putFloat("float", 2.71f) 128 | } 129 | } 130 | 131 | Assert.assertEquals(33, fragment.integer) 132 | Assert.assertEquals(false, fragment.boolean) 133 | Assert.assertEquals("pinkie pie", fragment.string) 134 | Assert.assertEquals(14L, fragment.long) 135 | Assert.assertEquals(3.14, fragment.double) 136 | Assert.assertEquals(2.71f, fragment.float) 137 | } 138 | 139 | fun testOptionalBindingsWithoutArguments() { 140 | class ArgumentsFragment : Fragment() { 141 | val integer by bindOptionalArgument("integer") 142 | val boolean by bindOptionalArgument("boolean") 143 | val string by bindOptionalArgument("string") 144 | val long by bindOptionalArgument("long") 145 | val double by bindOptionalArgument("double") 146 | val float by bindOptionalArgument("float") 147 | } 148 | 149 | val fragment = ArgumentsFragment().apply { 150 | arguments = Bundle() 151 | } 152 | 153 | Assert.assertEquals(null, fragment.integer) 154 | Assert.assertEquals(null, fragment.boolean) 155 | Assert.assertEquals(null, fragment.string) 156 | Assert.assertEquals(null, fragment.long) 157 | Assert.assertEquals(null, fragment.double) 158 | Assert.assertEquals(null, fragment.float) 159 | } 160 | 161 | fun testOptionalBindingsWithArguments() { 162 | class ArgumentsFragment : Fragment() { 163 | val integer by bindOptionalArgument("integer") 164 | val boolean by bindOptionalArgument("boolean") 165 | val string by bindOptionalArgument("string") 166 | val long by bindOptionalArgument("long") 167 | val double by bindOptionalArgument("double") 168 | val float by bindOptionalArgument("float") 169 | } 170 | 171 | val fragment = ArgumentsFragment().apply { 172 | arguments = Bundle().apply { 173 | putInt("integer", 33) 174 | putBoolean("boolean", false) 175 | putString("string", "pinkie pie") 176 | putLong("long", 14L) 177 | putDouble("double", 3.14) 178 | putFloat("float", 2.71f) 179 | } 180 | } 181 | 182 | Assert.assertEquals(33, fragment.integer) 183 | Assert.assertEquals(false, fragment.boolean) 184 | Assert.assertEquals("pinkie pie", fragment.string) 185 | Assert.assertEquals(14L, fragment.long) 186 | Assert.assertEquals(3.14, fragment.double) 187 | Assert.assertEquals(2.71f, fragment.float) 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /jetpack-bindings-preferences/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "com.android.library" 2 | apply plugin: "kotlin-android" 3 | 4 | android { 5 | compileSdkVersion projectCompileSdkVersion 6 | buildToolsVersion projectBuildToolsVersion 7 | 8 | defaultConfig { 9 | targetSdkVersion projectTargetSdkVersion 10 | minSdkVersion projectMinSdkVersion 11 | } 12 | 13 | sourceSets { 14 | main.java.srcDirs += 'src/main/kotlin' 15 | main.java.srcDirs += 'src/main/generated' 16 | 17 | androidTest.java.srcDirs += 'src/test/kotlin' 18 | } 19 | } 20 | 21 | dependencies { 22 | provided "com.android.support:support-v4:$supportVersion" 23 | provided "com.android.support:recyclerview-v7:$supportVersion" 24 | 25 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" 26 | } 27 | 28 | apply from: rootProject.file('gradle/gradle-mvn-push.gradle') 29 | -------------------------------------------------------------------------------- /jetpack-bindings-preferences/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_ARTIFACT_ID=jetpack-bindings-preferences 2 | POM_NAME=Jetpack Preferences Bindings 3 | POM_PACKAGING=aar 4 | -------------------------------------------------------------------------------- /jetpack-bindings-preferences/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /jetpack-bindings-preferences/src/main/kotlin/com/github/vmironov/jetpack/preferences/PreferencesBindings.kt: -------------------------------------------------------------------------------- 1 | package com.github.vmironov.jetpack.preferences 2 | 3 | import android.app.Dialog 4 | import android.app.Fragment 5 | import android.content.Context 6 | import android.content.SharedPreferences 7 | import android.preference.PreferenceManager 8 | import android.view.View 9 | import kotlin.properties.ReadWriteProperty 10 | import kotlin.reflect.KProperty 11 | 12 | inline fun Any.bindPreference(default: V, key: String? = null): ReadWriteProperty { 13 | return PreferencesVar(IdentityAdapter(V::class.java), this, key, { default }) 14 | } 15 | 16 | inline fun Any.bindPreference(noinline default: () -> V, key: String? = null): ReadWriteProperty { 17 | return PreferencesVar(IdentityAdapter(V::class.java), this, key, default) 18 | } 19 | 20 | inline fun Any.bindPreference(default: V, adapter: Adapter, key: String? = null): ReadWriteProperty { 21 | return PreferencesVar(adapter, this, key, { default }) 22 | } 23 | 24 | inline fun Any.bindPreference(noinline default: () -> V, adapter: Adapter, key: String? = null): ReadWriteProperty { 25 | return PreferencesVar(adapter, this, key, default) 26 | } 27 | 28 | inline fun > Any.bindEnumPreference(default: E, key: String? = null): ReadWriteProperty { 29 | return PreferencesVar(EnumAdapter(E::class.java), this, key, { default }) 30 | } 31 | 32 | inline fun > Any.bindEnumPreference(noinline default: () -> E, key: String? = null): ReadWriteProperty { 33 | return PreferencesVar(EnumAdapter(E::class.java), this, key, default) 34 | } 35 | 36 | inline fun Any.bindOptionalPreference(key: String? = null): ReadWriteProperty { 37 | return OptionalPreferencesVar(IdentityAdapter(V::class.java), this, key) 38 | } 39 | 40 | inline fun Any.bindOptionalPreference(adapter: Adapter, key: String? = null): ReadWriteProperty { 41 | return OptionalPreferencesVar(adapter, this, key) 42 | } 43 | 44 | inline fun > Any.bindOptionalEnumPreference(key: String? = null): ReadWriteProperty { 45 | return OptionalPreferencesVar(EnumAdapter(E::class.java), this, key) 46 | } 47 | 48 | interface PreferencesAware { 49 | companion object { 50 | operator fun invoke(factory: () -> SharedPreferences): PreferencesAware = object : PreferencesAware { 51 | override val preferences: SharedPreferences by lazy(LazyThreadSafetyMode.NONE) { 52 | factory() 53 | } 54 | } 55 | } 56 | 57 | val preferences: SharedPreferences 58 | } 59 | 60 | interface Adapter { 61 | fun type(): Class

62 | fun fromPreference(preference: P): V 63 | fun toPreference(value: V): P 64 | } 65 | 66 | class IdentityAdapter(val clazz: Class) : Adapter { 67 | override fun type(): Class = clazz 68 | override fun fromPreference(preference: T): T = preference 69 | override fun toPreference(value: T): T = value 70 | } 71 | 72 | class EnumAdapter>(val clazz: Class) : Adapter { 73 | override fun type(): Class = String::class.java 74 | override fun fromPreference(preference: String): E = java.lang.Enum.valueOf(clazz, preference) 75 | override fun toPreference(value: E): String = value.name 76 | } 77 | 78 | @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST") class PreferencesVar( 79 | private val adapter: Adapter, 80 | private val source: Any, 81 | private val key: String?, 82 | private val default: () -> V 83 | ) : ReadWriteProperty { 84 | private val preference = onGetPropertyFromClass(adapter.type()) 85 | 86 | private val preferences by lazy(LazyThreadSafetyMode.NONE) { 87 | onGetPreferencesFromSource(source) 88 | } 89 | 90 | override final operator fun getValue(thisRef: T, property: KProperty<*>): V { 91 | val name = key ?: property.name 92 | 93 | if (!preferences.contains(name)) { 94 | setValue(thisRef, property, default()) 95 | } 96 | 97 | return adapter.fromPreference(preference[preferences, name] as P) 98 | } 99 | 100 | override final operator fun setValue(thisRef: T, property: KProperty<*>, value: V) { 101 | preferences.edit().apply { 102 | preference.set(this, key ?: property.name, adapter.toPreference(value)) 103 | apply() 104 | } 105 | } 106 | } 107 | 108 | @Suppress("UNCHECKED_CAST") class OptionalPreferencesVar( 109 | private val adapter: Adapter, 110 | private val source: Any, 111 | private val key: String? 112 | ) : ReadWriteProperty { 113 | private val preference = onGetPropertyFromClass(adapter.type()) 114 | 115 | private val preferences by lazy(LazyThreadSafetyMode.NONE) { 116 | onGetPreferencesFromSource(source) 117 | } 118 | 119 | override operator fun getValue(thisRef: T, property: KProperty<*>): V? { 120 | val name = key ?: property.name 121 | 122 | return if (preferences.contains(name)) { 123 | adapter.fromPreference(preference[preferences, name] as P) 124 | } else { 125 | null 126 | } 127 | } 128 | 129 | override operator fun setValue(thisRef: T, property: KProperty<*>, value: V?) { 130 | preferences.edit().apply { 131 | val name = key ?: property.name 132 | 133 | if (value != null) { 134 | preference.set(this, name, adapter.toPreference(value)) 135 | } else { 136 | remove(name) 137 | } 138 | 139 | apply() 140 | } 141 | } 142 | } 143 | 144 | @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UNCHECKED_CAST") 145 | private fun onGetPropertyFromClass(clazz: Class<*>): Preference { 146 | return when (clazz) { 147 | kotlin.Boolean::class.java -> BooleanPreference 148 | kotlin.Float::class.java -> FloatPreference 149 | kotlin.Int::class.java -> IntPreference 150 | kotlin.Long::class.java -> LongPreference 151 | kotlin.String::class.java -> StringPreference 152 | 153 | java.lang.Boolean::class.java -> BooleanPreference 154 | java.lang.Float::class.java -> FloatPreference 155 | java.lang.Integer::class.java -> IntPreference 156 | java.lang.Long::class.java -> LongPreference 157 | java.lang.String::class.java -> StringPreference 158 | 159 | else -> throw UnsupportedOperationException("Unsupported preference type \"${clazz.canonicalName}\"") 160 | } as Preference 161 | } 162 | 163 | private fun onGetPreferencesFromSource(source: Any): SharedPreferences { 164 | return when { 165 | source is SharedPreferences -> source 166 | source is PreferencesAware -> source.preferences 167 | source is Fragment -> PreferenceManager.getDefaultSharedPreferences(source.activity) 168 | source is Context -> PreferenceManager.getDefaultSharedPreferences(source) 169 | 170 | SupportHelper.isFragment(source) -> SupportFragmentHelper.getPreferences(source) 171 | SupportHelper.isHolder(source) -> SupportRecyclerHelper.getPreferences(source) 172 | 173 | source is View -> PreferenceManager.getDefaultSharedPreferences(source.context) 174 | source is Dialog -> PreferenceManager.getDefaultSharedPreferences(source.context) 175 | 176 | else -> throw IllegalArgumentException("Unable to find \"SharedPreferences\" instance on type \"${source.javaClass.simpleName}\"") 177 | } 178 | } 179 | 180 | private interface Preference { 181 | operator fun set(editor: SharedPreferences.Editor, name: String, value: T): Unit 182 | operator fun get(preferences: SharedPreferences, name: String): T 183 | } 184 | 185 | private object BooleanPreference : Preference { 186 | override fun set(editor: SharedPreferences.Editor, name: String, value: Boolean): Unit { 187 | editor.putBoolean(name, value) 188 | } 189 | 190 | override fun get(preferences: SharedPreferences, name: String): Boolean { 191 | return preferences.getBoolean(name, false) 192 | } 193 | } 194 | 195 | private object FloatPreference : Preference { 196 | override fun set(editor: SharedPreferences.Editor, name: String, value: Float): Unit { 197 | editor.putFloat(name, value) 198 | } 199 | 200 | override fun get(preferences: SharedPreferences, name: String): Float { 201 | return preferences.getFloat(name, 0.0f) 202 | } 203 | } 204 | 205 | private object IntPreference : Preference { 206 | override fun set(editor: SharedPreferences.Editor, name: String, value: Int): Unit { 207 | editor.putInt(name, value) 208 | } 209 | 210 | override fun get(preferences: SharedPreferences, name: String): Int { 211 | return preferences.getInt(name, 0) 212 | } 213 | } 214 | 215 | private object LongPreference : Preference { 216 | override fun set(editor: SharedPreferences.Editor, name: String, value: Long): Unit { 217 | editor.putLong(name, value) 218 | } 219 | 220 | override fun get(preferences: SharedPreferences, name: String): Long { 221 | return preferences.getLong(name, 0L) 222 | } 223 | } 224 | 225 | private object StringPreference : Preference { 226 | override fun set(editor: SharedPreferences.Editor, name: String, value: String): Unit { 227 | editor.putString(name, value) 228 | } 229 | 230 | override fun get(preferences: SharedPreferences, name: String): String { 231 | return preferences.getString(name, "") 232 | } 233 | } 234 | -------------------------------------------------------------------------------- /jetpack-bindings-preferences/src/main/kotlin/com/github/vmironov/jetpack/preferences/SupportUtils.kt: -------------------------------------------------------------------------------- 1 | package com.github.vmironov.jetpack.preferences 2 | 3 | import android.content.SharedPreferences 4 | import android.preference.PreferenceManager 5 | 6 | internal object SupportHelper { 7 | private val FQNAME_SUPPORT_FRAGMENT = "android.support.v4.app.Fragment" 8 | private val FQNAME_RECYCLER_HOLDER = "android.support.v7.widget.RecyclerView.ViewHolder" 9 | 10 | private val HAS_SUPPORT_FRAGMENTS = hasClass(FQNAME_SUPPORT_FRAGMENT) 11 | private val HAS_RECYCLER_HOLDER = hasClass(FQNAME_RECYCLER_HOLDER) 12 | 13 | internal fun isFragment(target: Any): Boolean { 14 | return HAS_SUPPORT_FRAGMENTS && SupportFragmentHelper.isFragment(target) 15 | } 16 | 17 | internal fun isHolder(target: Any): Boolean { 18 | return HAS_RECYCLER_HOLDER && SupportRecyclerHelper.isHolder(target) 19 | } 20 | 21 | private fun hasClass(fqname: String): Boolean = try { 22 | Class.forName(fqname) != null 23 | } catch (exception: Exception) { 24 | false 25 | } 26 | } 27 | 28 | internal object SupportFragmentHelper { 29 | internal fun isFragment(target: Any): Boolean { 30 | return target is android.support.v4.app.Fragment 31 | } 32 | 33 | internal fun getPreferences(target: Any): SharedPreferences { 34 | return PreferenceManager.getDefaultSharedPreferences((target as android.support.v4.app.Fragment).context) 35 | } 36 | } 37 | 38 | internal object SupportRecyclerHelper { 39 | internal fun isHolder(target: Any): Boolean { 40 | return target is android.support.v7.widget.RecyclerView.ViewHolder 41 | } 42 | 43 | internal fun getPreferences(target: Any): SharedPreferences { 44 | return PreferenceManager.getDefaultSharedPreferences((target as android.support.v7.widget.RecyclerView.ViewHolder).itemView.context) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /jetpack-bindings-resources/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "com.android.library" 2 | apply plugin: "kotlin-android" 3 | 4 | android { 5 | compileSdkVersion projectCompileSdkVersion 6 | buildToolsVersion projectBuildToolsVersion 7 | 8 | defaultConfig { 9 | targetSdkVersion projectTargetSdkVersion 10 | minSdkVersion projectMinSdkVersion 11 | } 12 | 13 | sourceSets { 14 | main.java.srcDirs += 'src/main/kotlin' 15 | main.java.srcDirs += 'src/main/generated' 16 | } 17 | } 18 | 19 | dependencies { 20 | provided "com.android.support:support-v4:$supportVersion" 21 | provided "com.android.support:recyclerview-v7:$supportVersion" 22 | 23 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" 24 | } 25 | 26 | apply from: rootProject.file('gradle/gradle-mvn-push.gradle') 27 | -------------------------------------------------------------------------------- /jetpack-bindings-resources/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_ARTIFACT_ID=jetpack-bindings-resources 2 | POM_NAME=Jetpack Resource Bindings 3 | POM_PACKAGING=aar 4 | -------------------------------------------------------------------------------- /jetpack-bindings-resources/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /jetpack-bindings-resources/src/main/kotlin/com/github/vmironov/jetpack/resources/ResourcesBindings.kt: -------------------------------------------------------------------------------- 1 | package com.github.vmironov.jetpack.resources 2 | 3 | import android.app.Dialog 4 | import android.app.Fragment 5 | import android.content.Context 6 | import android.content.res.ColorStateList 7 | import android.content.res.Resources 8 | import android.graphics.drawable.Drawable 9 | import android.view.View 10 | import kotlin.properties.ReadOnlyProperty 11 | import kotlin.reflect.KProperty 12 | 13 | inline fun Any.bindResource(id: Int): ReadOnlyProperty { 14 | return ResourcesVal(T::class.java, this, id) 15 | } 16 | 17 | interface ResourcesAware { 18 | companion object { 19 | operator fun invoke(factory: () -> Resources): ResourcesAware = object : ResourcesAware { 20 | override val resources: Resources by lazy(LazyThreadSafetyMode.NONE) { 21 | factory() 22 | } 23 | } 24 | } 25 | 26 | val resources: Resources 27 | } 28 | 29 | @Suppress("UNCHECKED_CAST", "USELESS_CAST") class ResourcesVal( 30 | private val clazz: Class, 31 | private val source: Any, 32 | private val id: Int 33 | ) : ReadOnlyProperty { 34 | private var value: Any? = Unit 35 | 36 | override operator fun getValue(thisRef: T, property: KProperty<*>): V { 37 | if (value === Unit) { 38 | value = onLazyGetValue(when { 39 | source is ResourcesAware -> source.resources 40 | source is Context -> source.resources 41 | source is Fragment -> source.activity.resources 42 | source is Resources -> source as Resources 43 | source is View -> source.resources 44 | SupportHelper.isFragment(source) -> SupportFragmentHelper.getResources(source) 45 | SupportHelper.isHolder(source) -> SupportRecyclerHelper.getResources(source) 46 | source is Dialog -> source.context.resources 47 | else -> throw IllegalArgumentException("Unable to find resources on type ${source.javaClass.simpleName}") 48 | }) 49 | } 50 | 51 | return value as V 52 | } 53 | 54 | @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "DEPRECATED_SYMBOL_WITH_MESSAGE", "IMPLICIT_CAST_TO_ANY", "DEPRECATION") 55 | private fun onLazyGetValue(resources: Resources): V { 56 | val type = resources.getResourceTypeName(id) 57 | val typed = { desiredType: String, desiredClass: Class<*> -> 58 | desiredType == type && desiredClass.isAssignableFrom(clazz) 59 | } 60 | 61 | return when { 62 | typed("drawable", Drawable::class.java) -> resources.getDrawable(id) 63 | 64 | typed("bool", kotlin.Boolean::class.java) -> resources.getBoolean(id) 65 | typed("bool", java.lang.Boolean::class.java) -> resources.getBoolean(id) 66 | 67 | typed("integer", kotlin.Int::class.java) -> resources.getInteger(id) 68 | typed("integer", java.lang.Integer::class.java) -> resources.getInteger(id) 69 | 70 | typed("color", kotlin.Int::class.java) -> resources.getColor(id) 71 | typed("color", java.lang.Integer::class.java) -> resources.getColor(id) 72 | typed("color", ColorStateList::class.java) -> resources.getColorStateList(id) 73 | 74 | typed("dimen", kotlin.Float::class.java) -> resources.getDimension(id) 75 | typed("dimen", java.lang.Float::class.java) -> resources.getDimension(id) 76 | 77 | typed("dimen", kotlin.Int::class.java) -> resources.getDimension(id) 78 | typed("dimen", java.lang.Integer::class.java) -> resources.getDimension(id) 79 | 80 | typed("string", kotlin.String::class.java) -> resources.getString(id) 81 | typed("string", java.lang.String::class.java) -> resources.getString(id) 82 | 83 | typed("string", kotlin.CharSequence::class.java) -> resources.getText(id) 84 | typed("string", java.lang.CharSequence::class.java) -> resources.getText(id) 85 | 86 | typed("array", IntArray::class.java) -> resources.getIntArray(id) 87 | typed("array", Array::class.java) -> resources.getIntArray(id) 88 | typed("array", Array::class.java) -> resources.getIntArray(id) 89 | 90 | typed("array", Array::class.java) -> resources.getStringArray(id) 91 | typed("array", Array::class.java) -> resources.getStringArray(id) 92 | 93 | typed("array", Array::class.java) -> resources.getTextArray(id) 94 | typed("array", Array::class.java) -> resources.getTextArray(id) 95 | 96 | else -> throw UnsupportedOperationException("Unsupported resource (name = \"${resources.getResourceName(id)}\", type = \"${clazz.canonicalName}\")") 97 | } as V 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /jetpack-bindings-resources/src/main/kotlin/com/github/vmironov/jetpack/resources/SupportUtils.kt: -------------------------------------------------------------------------------- 1 | package com.github.vmironov.jetpack.resources 2 | 3 | import android.content.res.Resources 4 | 5 | internal object SupportHelper { 6 | private val FQNAME_SUPPORT_FRAGMENT = "android.support.v4.app.Fragment" 7 | private val FQNAME_RECYCLER_HOLDER = "android.support.v7.widget.RecyclerView.ViewHolder" 8 | 9 | private val HAS_SUPPORT_FRAGMENTS = hasClass(FQNAME_SUPPORT_FRAGMENT) 10 | private val HAS_RECYCLER_HOLDER = hasClass(FQNAME_RECYCLER_HOLDER) 11 | 12 | internal fun isFragment(target: Any): Boolean { 13 | return HAS_SUPPORT_FRAGMENTS && SupportFragmentHelper.isFragment(target) 14 | } 15 | 16 | internal fun isHolder(target: Any): Boolean { 17 | return HAS_RECYCLER_HOLDER && SupportRecyclerHelper.isHolder(target) 18 | } 19 | 20 | private fun hasClass(fqname: String): Boolean = try { 21 | Class.forName(fqname) != null 22 | } catch (exception: Exception) { 23 | false 24 | } 25 | } 26 | 27 | internal object SupportFragmentHelper { 28 | internal fun isFragment(target: Any): Boolean { 29 | return target is android.support.v4.app.Fragment 30 | } 31 | 32 | internal fun getResources(target: Any): Resources { 33 | return (target as android.support.v4.app.Fragment).resources 34 | } 35 | } 36 | 37 | internal object SupportRecyclerHelper { 38 | internal fun isHolder(target: Any): Boolean { 39 | return target is android.support.v7.widget.RecyclerView.ViewHolder 40 | } 41 | 42 | internal fun getResources(target: Any): Resources { 43 | return (target as android.support.v7.widget.RecyclerView.ViewHolder).itemView.resources 44 | } 45 | } 46 | 47 | 48 | -------------------------------------------------------------------------------- /jetpack-bindings-sample/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | dependencies { 3 | classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlinVersion" 4 | } 5 | } 6 | 7 | apply plugin: "com.android.application" 8 | apply plugin: "kotlin-android" 9 | apply plugin: "kotlin-android-extensions" 10 | 11 | android { 12 | compileSdkVersion projectCompileSdkVersion 13 | buildToolsVersion projectBuildToolsVersion 14 | 15 | defaultConfig { 16 | targetSdkVersion projectTargetSdkVersion 17 | minSdkVersion 21 18 | } 19 | 20 | sourceSets { 21 | main.java.srcDirs += 'src/main/kotlin' 22 | } 23 | } 24 | 25 | dependencies { 26 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" 27 | 28 | compile project(":jetpack-bindings-arguments") 29 | compile project(":jetpack-bindings-preferences") 30 | compile project(":jetpack-bindings-resources") 31 | } 32 | -------------------------------------------------------------------------------- /jetpack-bindings-sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /jetpack-bindings-sample/src/main/kotlin/com/github/vmironov/jetpack/sample/SampleActivity.kt: -------------------------------------------------------------------------------- 1 | package com.github.vmironov.jetpack.sample 2 | 3 | import android.app.Activity 4 | import android.os.Bundle 5 | 6 | class SampleActivity : Activity() { 7 | override fun onCreate(savedInstanceState: Bundle?) { 8 | super.onCreate(savedInstanceState) 9 | setContentView(R.layout.activity_sample) 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /jetpack-bindings-sample/src/main/kotlin/com/github/vmironov/jetpack/sample/SampleFragment.kt: -------------------------------------------------------------------------------- 1 | package com.github.vmironov.jetpack.sample 2 | 3 | import android.app.Fragment 4 | import android.graphics.drawable.ColorDrawable 5 | import android.os.Bundle 6 | import android.util.TypedValue 7 | import android.view.* 8 | import com.github.vmironov.jetpack.preferences.bindOptionalPreference 9 | import com.github.vmironov.jetpack.resources.bindResource 10 | 11 | import kotlinx.android.synthetic.main.fragment_sample.* 12 | 13 | class SampleFragment : Fragment() { 14 | private var firstNameValue by bindOptionalPreference() 15 | private var lastNameValue by bindOptionalPreference() 16 | 17 | private val firstNameLabel by bindResource(R.string.first_name_label) 18 | private val firstNameHint by bindResource(R.string.first_name_hint) 19 | 20 | private val lastNameLabel by bindResource(R.string.last_name_label) 21 | private val lastNameHint by bindResource(R.string.last_name_hint) 22 | 23 | private val paddingTiny by bindResource(R.dimen.padding_tiny) 24 | private val paddingSmall by bindResource(R.dimen.padding_small) 25 | private val paddingLarge by bindResource(R.dimen.padding_large) 26 | 27 | private val colorPrimary by bindResource(R.color.primary) 28 | private val colorBackground by bindResource(R.color.color_background) 29 | private val colorText by bindResource(R.color.color_text) 30 | private val colorHint by bindResource(R.color.color_hint) 31 | 32 | private val fontSmall by bindResource(R.dimen.font_small) 33 | private val fontNormal by bindResource(R.dimen.font_normal) 34 | 35 | override fun onCreate(savedInstanceState: Bundle?) { 36 | super.onCreate(savedInstanceState) 37 | setHasOptionsMenu(true) 38 | } 39 | 40 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { 41 | return inflater.inflate(R.layout.fragment_sample, container, false) 42 | } 43 | 44 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 45 | super.onViewCreated(view, savedInstanceState) 46 | 47 | view.background = ColorDrawable(colorBackground) 48 | view.setPadding(paddingLarge, paddingLarge, paddingLarge, paddingLarge) 49 | 50 | first_name_label.text = firstNameLabel 51 | first_name_label.setPadding(paddingSmall, paddingTiny, paddingSmall, paddingTiny) 52 | first_name_label.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSmall) 53 | first_name_label.setTextColor(colorPrimary) 54 | 55 | last_name_label.text = lastNameLabel 56 | last_name_label.setPadding(paddingSmall, paddingTiny, paddingSmall, paddingTiny) 57 | last_name_label.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSmall) 58 | last_name_label.setTextColor(colorPrimary) 59 | 60 | first_name_input.hint = firstNameHint 61 | first_name_input.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontNormal) 62 | first_name_input.setHintTextColor(colorHint) 63 | first_name_input.setText(firstNameValue.orEmpty()) 64 | first_name_input.setTextColor(colorText) 65 | 66 | last_name_input.hint = lastNameHint 67 | last_name_input.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontNormal) 68 | last_name_input.setTextColor(colorText) 69 | last_name_input.setText(lastNameValue.orEmpty()) 70 | last_name_input.setHintTextColor(colorHint) 71 | } 72 | 73 | override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { 74 | super.onCreateOptionsMenu(menu, inflater) 75 | inflater.inflate(R.menu.menu_sample, menu) 76 | } 77 | 78 | override fun onOptionsItemSelected(item: MenuItem): Boolean { 79 | when (item.itemId) { 80 | R.id.menu_done -> { 81 | firstNameValue = first_name_input.text?.toString() 82 | lastNameValue = last_name_input.text?.toString() 83 | } 84 | } 85 | 86 | return super.onOptionsItemSelected(item) 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /jetpack-bindings-sample/src/main/res/drawable/ic_done_white_24dp.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /jetpack-bindings-sample/src/main/res/layout/activity_sample.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /jetpack-bindings-sample/src/main/res/layout/fragment_sample.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 12 | 13 | 17 | 18 | 21 | 22 | 27 | 28 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /jetpack-bindings-sample/src/main/res/menu/menu_sample.xml: -------------------------------------------------------------------------------- 1 | 2 |

3 | 8 | -------------------------------------------------------------------------------- /jetpack-bindings-sample/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | 6 | #FFFFFF 7 | #FFFFFF 8 | 9 | #FF000000 10 | #30000000 11 | 12 | -------------------------------------------------------------------------------- /jetpack-bindings-sample/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 2dp 4 | 4dp 5 | 8dp 6 | 16dp 7 | 32dp 8 | 9 | 12sp 10 | 15sp 11 | 18sp 12 | -------------------------------------------------------------------------------- /jetpack-bindings-sample/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Jetpack Sample 4 | 5 | First name: 6 | Enter your first name 7 | 8 | Last name: 9 | Enter your last name 10 | 11 | Done 12 | 13 | -------------------------------------------------------------------------------- /jetpack-bindings-sample/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':jetpack-bindings-arguments' 2 | include ':jetpack-bindings-preferences' 3 | include ':jetpack-bindings-resources' 4 | include ':jetpack-bindings-sample' 5 | --------------------------------------------------------------------------------