├── .gitignore ├── CHANGELOG.md ├── Jenkinsfile ├── LICENSE.txt ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── github │ │ └── nitrico │ │ └── lastadapter_sample │ │ ├── data │ │ ├── Car.java │ │ ├── Data.kt │ │ ├── Header.kt │ │ ├── Person.kt │ │ ├── Point.kt │ │ └── StableData.kt │ │ └── ui │ │ ├── JavaListFragment.java │ │ ├── KotlinListFragment.kt │ │ ├── ListFragment.kt │ │ └── MainActivity.kt │ └── res │ ├── layout │ ├── activity_main.xml │ ├── fragment_list.xml │ ├── item_car.xml │ ├── item_header.xml │ ├── item_header_first.xml │ ├── item_person.xml │ └── item_point.xml │ ├── menu │ └── main.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── mipmap-xxxhdpi │ └── ic_launcher.png │ └── values │ ├── colors.xml │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── lastadapter ├── .gitignore ├── build.gradle ├── proguard-rules.pro ├── publish.gradle └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── com │ └── github │ └── nitrico │ └── lastadapter │ ├── Holder.kt │ ├── Interfaces.kt │ ├── LastAdapter.kt │ ├── ObservableListCallback.kt │ └── Types.kt └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | /local.properties 3 | .idea 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .gradle 10 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Change Log 2 | ========== 3 | 4 | Version 2.3.0 *(2017-11-28)* 5 | ---------------------------- 6 | - **Fix**: [`IndexOutOfBoundExeption` when not using ObservableList](https://github.com/nitrico/LastAdapter/issues/28) 7 | - Update target SDK to 27 8 | - Update Kotlin to version 1.2.0 9 | - Update support libraries to version 27.0.2 10 | - Update Android build tools to version 27.0.1 11 | - Update Android Gradle Plugin to version 3.0.1 12 | 13 | Version 2.2.0 *(2017-04-01)* 14 | ---------------------------- 15 | 16 | **Breaking changes** 17 | - **New:** Removed `with` constructor – Use default constructors instead. 18 | - **New:** Added `onCreate` callback as it is a more convenient place to set the click listeners. 19 | - **New:** Click listeners are not set in on `onCreate`. 20 | - **New:** Added support for different variable names depending on the type, while still support the old "only one variable name"-style for all types. 21 | - **New:** ViewHolder class renamed to Holder. 22 | - Smaller size despite including new features! 23 | 24 | Version 2.1.0 *(2017-03-26)* 25 | ---------------------------- 26 | 27 | **Breaking changes** 28 | - **New:** The ViewHolder is now the only argument in the callbacks. It was added to add ItemTouchHelper support but since the binding, the position and the view are inside the ViewHolder, this is actually the only argument needed. 29 | - In Kotlin, arguments for Handlers (item & position) need to be explicitly declared now. 30 | - Updated dependencies: Kotlin 1.1.1, Support libraries 25.3.0, Gradle 3.3, Gradle plugin 2.3.0. 31 | 32 | Version 1.2.4 *(2016-11-07)* 33 | ---------------------------- 34 | 35 | - **Fix**: [Issue with support library 25.0.0](https://github.com/nitrico/LastAdapter/issues/9). 36 | 37 | Version 1.2.3 *(2016-09-23)* 38 | ---------------------------- 39 | 40 | - Updated to Kotlin 1.0.4 41 | 42 | 43 | Version 1.2.2 *(2016-09-09)* 44 | ---------------------------- 45 | 46 | - **Fix:** [IllegalStateException: reference.get() must not be null](https://github.com/nitrico/LastAdapter/issues/5). 47 | - Removed unneeded "generics". 48 | - Dependencies updated (which increased min SDK version from 7 to 9). 49 | 50 | 51 | Version 1.2.1 *(2016-08-12)* 52 | ---------------------------- 53 | 54 | - Code cleanup. 55 | 56 | 57 | Version 1.2.0 *(2016-08-09)* 58 | ---------------------------- 59 | 60 | - **New:** Added `type` parameter to `onBind`, `onClick` and `onLongClick` methods in their respective interfaces. It is an int value that matches the layout resource id used for each item. 61 | - **Fix:** `for` loop range in `ListReference.onItemRangeMoved`. 62 | - `ListReference` class moved to a new file. 63 | - Dependencies updated. 64 | 65 | 66 | Version 1.1.0 *(2016-07-03)* 67 | ---------------------------- 68 | 69 | - **New:** Added lambda support in Kotlin for `onBind`, `onClick`, `onLongClick` and `layout`. 70 | 71 | 72 | Version 1.0.0 *(2016-06-30)* 73 | ---------------------------- 74 | 75 | - Initial release. 76 | -------------------------------------------------------------------------------- /Jenkinsfile: -------------------------------------------------------------------------------- 1 | pipeline { 2 | agent any 3 | stages { 4 | stage('Build') { 5 | steps { 6 | git(url: 'https://github.com/nitrico/LastAdapter', branch: 'master') 7 | } 8 | } 9 | } 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 2016 Miguel Ángel Moreno 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 | [![Download](https://api.bintray.com/packages/moreno/maven/lastadapter/images/download.svg)](https://bintray.com/moreno/maven/lastadapter/_latestVersion) 2 | [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-LastAdapter-brightgreen.svg?style=flat)](http://android-arsenal.com/details/1/3810) 3 | [![License](https://img.shields.io/badge/License-Apache%202.0-orange.svg)](https://opensource.org/licenses/Apache-2.0) 4 | [![Gitter](https://badges.gitter.im/nitrico/LastAdapter.svg)](https://gitter.im/nitrico/LastAdapter?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) 5 | 6 | # LastAdapter 7 | 8 | **Don't write a RecyclerView adapter again. Not even a ViewHolder!** 9 | 10 | * Based on [**Android Data Binding**](https://developer.android.com/topic/libraries/data-binding/index.html) 11 | * Written in [**Kotlin**](http://kotlinlang.org) 12 | * No need to write the adapter 13 | * No need to write the viewholders 14 | * No need to modify your model classes 15 | * No need to notify the adapter when data set changes 16 | * Supports multiple item view types 17 | * Optional Callbacks/Listeners 18 | * Very fast — no reflection 19 | * Super easy API 20 | * Tiny size: **~30 KB** 21 | * Minimum Android SDK: **9** 22 | 23 | 24 | ## Setup 25 | 26 | ### Gradle 27 | 28 | ```gradle 29 | // apply plugin: 'kotlin-kapt' // this line only for Kotlin projects 30 | 31 | android { 32 | ... 33 | dataBinding.enabled true 34 | } 35 | 36 | dependencies { 37 | compile 'com.github.nitrico.lastadapter:lastadapter:2.3.0' 38 | // kapt 'com.android.databinding:compiler:GRADLE_PLUGIN_VERSION' // this line only for Kotlin projects 39 | } 40 | ``` 41 | 42 | 43 | ## Usage 44 | 45 | Create your item layouts with `` as root: 46 | 47 | ```xml 48 | 49 | 50 | 51 | 52 | 53 | 54 | 58 | 59 | 60 | ``` 61 | 62 | **It is important for all the item types to have the same variable name**, in this case "item". 63 | This name is passed to the adapter builder as BR.variableName, in this case BR.item: 64 | 65 | ```java 66 | // Java 67 | new LastAdapter(listOfItems, BR.item) 68 | .map(Header.class, R.layout.item_header) 69 | .map(Point.class, R.layout.item_point) 70 | .into(recyclerView); 71 | ``` 72 | ```kotlin 73 | // Kotlin 74 | LastAdapter(listOfItems, BR.item) 75 | .map
(R.layout.item_header) 76 | .map(R.layout.item_point) 77 | .into(recyclerView) 78 | ``` 79 | 80 | The list of items can be an `ObservableList` if you want to get the adapter **automatically updated** when its content changes, or a simple `List` if you don't need to use this feature. 81 | 82 | 83 | ### LayoutHandler 84 | 85 | The LayoutHandler interface allows you to use different layouts based on more complex criteria. Its one single method receives the item and the position and returns the layout resource id. 86 | 87 | ```java 88 | // Java sample 89 | new LastAdapter(listOfItems, BR.item) 90 | .handler(handler) 91 | .into(recyclerView); 92 | 93 | private LayoutHandler handler = new LayoutHandler() { 94 | @Override public int getItemLayout(@NotNull Object item, int position) { 95 | if (item instanceof Header) { 96 | return (position == 0) ? R.layout.item_header_first : R.layout.item_header; 97 | } else { 98 | return R.layout.item_point; 99 | } 100 | } 101 | }; 102 | ``` 103 | ```kotlin 104 | // Kotlin sample 105 | LastAdapter(listOfItems, BR.item).layout { item, position -> 106 | when (item) { 107 | is Header -> if (position == 0) R.layout.item_header_first else R.layout.item_header 108 | else -> R.layout.item_point 109 | } 110 | }.into(recyclerView) 111 | ``` 112 | 113 | For further information, please take a look at [my article at Medium](https://medium.com/@miguelangelmoreno/dont-write-recyclerview-adapters-b1dbc2c683bb). 114 | 115 | ### Custom fonts 116 | 117 | You might also want to try [**FontBinder**](https://github.com/nitrico/FontBinder) to easily use custom fonts in your XML layouts. 118 | 119 | 120 | ## Acknowledgments 121 | 122 | Thanks to **Yigit Boyar** and **George Mount** for [this talk](https://realm.io/news/data-binding-android-boyar-mount/). 123 | 124 | 125 | ## Author 126 | 127 | #### Miguel Ángel Moreno 128 | 129 | I'm open to new job positions - Contact me! 130 | 131 | |[AngelList](https://angel.co/miguelangelmoreno)|[Email](mailto:nitrico@gmail.com)|[Facebook](https://www.facebook.com/miguelangelmoreno)|[Google+](https://plus.google.com/+Miguel%C3%81ngelMorenoS) |[Linked.in](https://www.linkedin.com/in/morenomiguelangel)|[Twitter](https://twitter.com/nitrico/) 132 | |---|---|---|---|---|---| 133 | 134 | 135 | ## License 136 | 137 | ```txt 138 | Copyright 2016 Miguel Ángel Moreno 139 | 140 | Licensed under the Apache License, Version 2.0 (the "License"); 141 | you may not use this file except in compliance with the License. 142 | You may obtain a copy of the License at 143 | 144 | http://www.apache.org/licenses/LICENSE-2.0 145 | 146 | Unless required by applicable law or agreed to in writing, software 147 | distributed under the License is distributed on an "AS IS" BASIS, 148 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 149 | See the License for the specific language governing permissions and 150 | limitations under the License. 151 | ``` 152 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | id 'kotlin-android' 4 | id 'kotlin-android-extensions' 5 | id 'kotlin-kapt' 6 | } 7 | 8 | android { 9 | compileSdkVersion versions.sdkTarget 10 | buildToolsVersion versions.buildTools 11 | defaultConfig { 12 | applicationId "com.github.nitrico.lastadapter_sample" 13 | minSdkVersion versions.sdkMin 14 | targetSdkVersion versions.sdkTarget 15 | } 16 | dataBinding.enabled true 17 | } 18 | 19 | dependencies { 20 | compile "com.android.support:appcompat-v7:$versions.support" 21 | compile "com.android.support:cardview-v7:$versions.support" 22 | compile "com.android.support:design:$versions.support" 23 | compile "com.android.support:recyclerview-v7:$versions.support" 24 | compile "org.jetbrains.kotlin:kotlin-stdlib:$versions.kotlin" 25 | kapt "com.android.databinding:compiler:$versions.gradlePlugin" 26 | compile project(":lastadapter") 27 | } 28 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in C:\Android\SDK/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /app/src/main/java/com/github/nitrico/lastadapter_sample/data/Car.java: -------------------------------------------------------------------------------- 1 | package com.github.nitrico.lastadapter_sample.data; 2 | 3 | import com.github.nitrico.lastadapter.StableId; 4 | 5 | public class Car implements StableId { 6 | 7 | private final Long serialNumber; 8 | private final String model; 9 | 10 | public Car(Long serialNumber, String model) { 11 | this.serialNumber = serialNumber; 12 | this.model = model; 13 | } 14 | 15 | public Long getSerialNumber() { 16 | return serialNumber; 17 | } 18 | 19 | public String getModel() { 20 | return model; 21 | } 22 | 23 | @Override 24 | public long getStableId() { 25 | return serialNumber; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /app/src/main/java/com/github/nitrico/lastadapter_sample/data/Data.kt: -------------------------------------------------------------------------------- 1 | package com.github.nitrico.lastadapter_sample.data 2 | 3 | import android.databinding.ObservableArrayList 4 | 5 | object Data { 6 | 7 | val items = ObservableArrayList().apply { 8 | add(Header("Header 1")) 9 | add(Point(1, 1)) 10 | add(Header("Header 2")) 11 | add(Point(2, 1)) 12 | add(Point(2, 2)) 13 | add(Header("Header 3")) 14 | add(Point(3, 1)) 15 | add(Point(3, 2)) 16 | add(Car(1899393, "911 Carrera")) 17 | add(Point(3, 3)) 18 | add(Header("Header 4")) 19 | add(Point(4, 1)) 20 | add(Point(4, 2)) 21 | add(Point(4, 3)) 22 | add(Person(99098, "Miguel Ángel", "Moreno")) 23 | add(Point(4, 4)) 24 | add(Header("Header 5")) 25 | add(Point(5, 1)) 26 | add(Point(5, 2)) 27 | add(Point(5, 3)) 28 | add(Point(5, 4)) 29 | add(Point(5, 5)) 30 | add(Header("Header 6")) 31 | add(Point(6, 1)) 32 | add(Point(6, 2)) 33 | add(Point(6, 3)) 34 | add(Point(6, 4)) 35 | add(Point(6, 5)) 36 | add(Point(6, 6)) 37 | add(Header("Header 7")) 38 | add(Point(7, 1)) 39 | add(Point(7, 2)) 40 | add(Point(7, 3)) 41 | add(Point(7, 4)) 42 | add(Point(7, 5)) 43 | add(Point(7, 6)) 44 | add(Point(7, 7)) 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /app/src/main/java/com/github/nitrico/lastadapter_sample/data/Header.kt: -------------------------------------------------------------------------------- 1 | package com.github.nitrico.lastadapter_sample.data 2 | 3 | import android.view.View 4 | import android.widget.Toast 5 | 6 | class Header(val text: String) { 7 | 8 | fun onItemClick(v: View) { 9 | Toast.makeText(v.context, "Click on Header $text", Toast.LENGTH_SHORT).show() 10 | } 11 | 12 | fun onItemLongClick(v: View): Boolean { 13 | Toast.makeText(v.context, "Long click on Header $text", Toast.LENGTH_SHORT).show() 14 | return true 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /app/src/main/java/com/github/nitrico/lastadapter_sample/data/Person.kt: -------------------------------------------------------------------------------- 1 | package com.github.nitrico.lastadapter_sample.data 2 | 3 | import com.github.nitrico.lastadapter.StableId 4 | 5 | class Person(val id: Long, val name: String, val surname: String) : StableId { 6 | 7 | override val stableId = id 8 | 9 | } 10 | -------------------------------------------------------------------------------- /app/src/main/java/com/github/nitrico/lastadapter_sample/data/Point.kt: -------------------------------------------------------------------------------- 1 | package com.github.nitrico.lastadapter_sample.data 2 | 3 | import android.view.View 4 | import android.widget.Toast 5 | 6 | class Point(val x: Int, val y: Int) { 7 | 8 | fun onItemClick(v: View) { 9 | Toast.makeText(v.context, "Click on Point ($x,$y)", Toast.LENGTH_SHORT).show() 10 | } 11 | 12 | fun onItemLongClick(v: View): Boolean { 13 | Toast.makeText(v.context, "Long click on Point ($x,$y)", Toast.LENGTH_SHORT).show() 14 | return true 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /app/src/main/java/com/github/nitrico/lastadapter_sample/data/StableData.kt: -------------------------------------------------------------------------------- 1 | package com.github.nitrico.lastadapter_sample.data 2 | 3 | import android.databinding.ObservableArrayList 4 | 5 | object StableData { 6 | 7 | val items = ObservableArrayList().apply { 8 | add(Car(1899393, "911 Carrera")) 9 | add(Car(392840, "911 Carrera")) 10 | add(Car(3928304, "911 Carrera")) 11 | //add(Header("Header")) 12 | add(Car(329, "911 Carrera")) 13 | add(Car(95084, "911 Carrera")) 14 | add(Car(466695, "911 Carrera")) 15 | add(Car(908456, "911 Carrera")) 16 | add(Car(49308, "911 Carrera")) 17 | add(Person(10001, "Miguel Ángel", "Moreno")) 18 | add(Person(10002, "Miguel Ángel", "Moreno")) 19 | add(Person(10003, "Miguel Ángel", "Moreno")) 20 | add(Person(10004, "Miguel Ángel", "Moreno")) 21 | add(Person(10005, "Miguel Ángel", "Moreno")) 22 | add(Person(10006, "Miguel Ángel", "Moreno")) 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /app/src/main/java/com/github/nitrico/lastadapter_sample/ui/JavaListFragment.java: -------------------------------------------------------------------------------- 1 | package com.github.nitrico.lastadapter_sample.ui; 2 | 3 | import android.content.Context; 4 | import android.os.Bundle; 5 | import android.util.Log; 6 | import android.view.View; 7 | import android.widget.Toast; 8 | import com.github.nitrico.lastadapter.ItemType; 9 | import com.github.nitrico.lastadapter.LastAdapter; 10 | import com.github.nitrico.lastadapter.LayoutHandler; 11 | import com.github.nitrico.lastadapter.BaseType; 12 | import com.github.nitrico.lastadapter.TypeHandler; 13 | import com.github.nitrico.lastadapter.Holder; 14 | import com.github.nitrico.lastadapter_sample.BR; 15 | import com.github.nitrico.lastadapter_sample.R; 16 | import com.github.nitrico.lastadapter_sample.data.Car; 17 | import com.github.nitrico.lastadapter_sample.data.Data; 18 | import com.github.nitrico.lastadapter_sample.data.Header; 19 | import com.github.nitrico.lastadapter_sample.data.Person; 20 | import com.github.nitrico.lastadapter_sample.data.Point; 21 | import com.github.nitrico.lastadapter_sample.data.StableData; 22 | import com.github.nitrico.lastadapter_sample.databinding.ItemCarBinding; 23 | import com.github.nitrico.lastadapter_sample.databinding.ItemHeaderBinding; 24 | import com.github.nitrico.lastadapter_sample.databinding.ItemHeaderFirstBinding; 25 | import com.github.nitrico.lastadapter_sample.databinding.ItemPersonBinding; 26 | import com.github.nitrico.lastadapter_sample.databinding.ItemPointBinding; 27 | import org.jetbrains.annotations.NotNull; 28 | import org.jetbrains.annotations.Nullable; 29 | import java.util.List; 30 | 31 | public class JavaListFragment extends ListFragment { 32 | 33 | public static final String TAG = JavaListFragment.class.getSimpleName(); 34 | 35 | private final ItemType typeHeaderFirst = new ItemType(R.layout.item_header_first) { 36 | @Override 37 | public void onCreate(@NotNull final Holder holder) { 38 | holder.itemView.setOnClickListener(new View.OnClickListener() { 39 | @Override 40 | public void onClick(View v) { 41 | toast(getContext(), "Clicked " +holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 42 | } 43 | }); 44 | } 45 | @Override 46 | public void onBind(@NotNull Holder holder) { 47 | Log.d(TAG, "Bound " + holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 48 | } 49 | @Override 50 | public void onRecycle(@NotNull Holder holder) { 51 | Log.d(TAG, "Recycled " + holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 52 | } 53 | }; 54 | 55 | private final ItemType typeHeader = new ItemType(R.layout.item_header) { 56 | @Override 57 | public void onCreate(final @NotNull Holder holder) { 58 | holder.itemView.setOnClickListener(new View.OnClickListener() { 59 | @Override 60 | public void onClick(View v) { 61 | toast(getContext(), "Clicked " +holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 62 | } 63 | }); 64 | } 65 | @Override 66 | public void onBind(@NotNull Holder holder) { 67 | Log.d(TAG, "Bound " + holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 68 | } 69 | @Override 70 | public void onRecycle(@NotNull Holder holder) { 71 | Log.d(TAG, "Recycled " + holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 72 | } 73 | }; 74 | 75 | private final ItemType typePoint = new ItemType(R.layout.item_point) { 76 | @Override 77 | public void onCreate(final @NotNull Holder holder) { 78 | holder.itemView.setOnClickListener(new View.OnClickListener() { 79 | @Override 80 | public void onClick(View v) { 81 | toast(getContext(), "Clicked " +holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 82 | } 83 | }); 84 | } 85 | @Override 86 | public void onBind(@NotNull Holder holder) { 87 | Log.d(TAG, "Bound " + holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 88 | } 89 | @Override 90 | public void onRecycle(@NotNull Holder holder) { 91 | Log.d(TAG, "Recycled " + holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 92 | } 93 | }; 94 | 95 | private final ItemType typeCar = new ItemType(R.layout.item_car) { 96 | @Override 97 | public void onCreate(final @NotNull Holder holder) { 98 | holder.itemView.setOnClickListener(new View.OnClickListener() { 99 | @Override 100 | public void onClick(View v) { 101 | toast(getContext(), "Clicked " +holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 102 | } 103 | }); 104 | } 105 | @Override 106 | public void onBind(@NotNull Holder holder) { 107 | Log.d(TAG, "Bound " + holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 108 | } 109 | @Override 110 | public void onRecycle(@NotNull Holder holder) { 111 | Log.d(TAG, "Recycled " + holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 112 | } 113 | }; 114 | 115 | private final ItemType typePerson = new ItemType(R.layout.item_person) { 116 | @Override 117 | public void onCreate(final @NotNull Holder holder) { 118 | holder.itemView.setOnClickListener(new View.OnClickListener() { 119 | @Override 120 | public void onClick(View v) { 121 | toast(getContext(), "Clicked " +holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 122 | } 123 | }); 124 | } 125 | @Override 126 | public void onBind(@NotNull Holder holder) { 127 | Log.d(TAG, "Bound " + holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 128 | } 129 | @Override 130 | public void onRecycle(@NotNull Holder holder) { 131 | Log.d(TAG, "Recycled " + holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 132 | } 133 | }; 134 | 135 | 136 | public JavaListFragment() { } 137 | 138 | @Override 139 | public void onActivityCreated(@Nullable Bundle savedInstanceState) { 140 | super.onActivityCreated(savedInstanceState); 141 | 142 | List items = Data.INSTANCE.getItems(); 143 | boolean stableIds = items == StableData.INSTANCE.getItems(); 144 | 145 | //setMapAdapter(items, stableIds); 146 | //setMapAdapterWithListeners(items, stableIds); 147 | //setLayoutHandlerAdapter(items, stableIds); 148 | setTypeHandlerAdapter(items, stableIds); 149 | } 150 | 151 | 152 | private void setMapAdapter(List items, boolean stableIds) { 153 | new LastAdapter(items) 154 | .map(Car.class, R.layout.item_car) 155 | .map(Person.class, R.layout.item_person) 156 | .map(Header.class, R.layout.item_header) 157 | .map(Point.class, R.layout.item_point) 158 | .into(list); 159 | } 160 | 161 | private void setMapAdapterWithListeners(List items, boolean stableIds) { 162 | new LastAdapter(items, BR.item, stableIds) 163 | .map(Car.class, typeCar) 164 | .map(Person.class, typePerson) 165 | .map(Point.class, new ItemType(R.layout.item_point) { 166 | @Override 167 | public void onBind(@NotNull Holder holder) { 168 | Log.d(TAG, "Bound " + holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 169 | } 170 | @Override 171 | public void onRecycle(@NotNull Holder holder) { 172 | Log.d(TAG, "Recycled " + holder.getBinding().getItem() + " at #" + holder.getAdapterPosition()); 173 | } 174 | }) 175 | .map(Header.class, typeHeader) 176 | .into(list); 177 | } 178 | 179 | private void setLayoutHandlerAdapter(List items, boolean stableIds) { 180 | new LastAdapter(items, BR.item, stableIds).handler(new LayoutHandler() { 181 | @Override 182 | public int getItemLayout(@NotNull Object item, int position) { 183 | if (item instanceof Header) return position == 0 ? R.layout.item_header_first : R.layout.item_header; 184 | else if (item instanceof Point) return R.layout.item_point; 185 | else if (item instanceof Person) return R.layout.item_person; 186 | else if (item instanceof Car) return R.layout.item_car; 187 | else return -1; 188 | } 189 | }).into(list); 190 | } 191 | 192 | private void setTypeHandlerAdapter(List items, boolean stableIds) { 193 | new LastAdapter(items, BR.item, stableIds).handler(new TypeHandler() { 194 | @Override 195 | public BaseType getItemType(@NotNull Object item, int position) { 196 | if (item instanceof Header) return position == 0 ? typeHeaderFirst : typeHeader; 197 | else if (item instanceof Point) return typePoint; 198 | else if (item instanceof Person) return typePerson; 199 | else if (item instanceof Car) return typeCar; 200 | return null; 201 | } 202 | }).into(list); 203 | } 204 | 205 | private static void toast(Context context, String text) { 206 | Toast.makeText(context, text, Toast.LENGTH_SHORT).show(); 207 | } 208 | 209 | } 210 | -------------------------------------------------------------------------------- /app/src/main/java/com/github/nitrico/lastadapter_sample/ui/KotlinListFragment.kt: -------------------------------------------------------------------------------- 1 | package com.github.nitrico.lastadapter_sample.ui 2 | 3 | import android.content.Context 4 | import android.os.Bundle 5 | import android.widget.Toast 6 | import com.github.nitrico.lastadapter.LastAdapter 7 | import com.github.nitrico.lastadapter.Type 8 | import com.github.nitrico.lastadapter_sample.BR 9 | import com.github.nitrico.lastadapter_sample.R 10 | import com.github.nitrico.lastadapter_sample.data.* 11 | import com.github.nitrico.lastadapter_sample.databinding.* 12 | 13 | class KotlinListFragment : ListFragment() { 14 | 15 | private val typeHeader = Type(R.layout.item_header) 16 | .onCreate { println("Created ${it.binding.item} at #${it.adapterPosition}") } 17 | .onBind { println("Bound ${it.binding.item} at #${it.adapterPosition}") } 18 | .onRecycle { println("Recycled ${it.binding.item} at #${it.adapterPosition}") } 19 | .onClick { activity.toast("Clicked #${it.adapterPosition}: ${it.binding.item}") } 20 | .onLongClick { activity.toast("Long-clicked #${it.adapterPosition}: ${it.binding.item}") } 21 | 22 | private val typeHeaderFirst = Type(R.layout.item_header_first) 23 | .onCreate { println("Created ${it.binding.item} at #${it.adapterPosition}") } 24 | .onBind { println("Bound ${it.binding.item} at #${it.adapterPosition}") } 25 | .onRecycle { println("Recycled ${it.binding.item} at #${it.adapterPosition}") } 26 | .onClick { activity.toast("Clicked #${it.adapterPosition}: ${it.binding.item}") } 27 | .onLongClick { activity.toast("Long-clicked #${it.adapterPosition}: ${it.binding.item}") } 28 | 29 | private val typePoint = Type(R.layout.item_point) 30 | .onCreate { println("Created ${it.binding.item} at #${it.adapterPosition}") } 31 | .onBind { println("Bound ${it.binding.item} at #${it.adapterPosition}") } 32 | .onRecycle { println("Recycled ${it.binding.item} at #${it.adapterPosition}") } 33 | .onClick { activity.toast("Clicked #${it.adapterPosition}: ${it.binding.item}") } 34 | .onLongClick { activity.toast("Long-clicked #${it.adapterPosition}: ${it.binding.item}") } 35 | 36 | private val typeCar = Type(R.layout.item_car) 37 | .onCreate { println("Created ${it.binding.item} at #${it.adapterPosition}") } 38 | .onBind { println("Bound ${it.binding.item} at #${it.adapterPosition}") } 39 | .onRecycle { println("Recycled ${it.binding.item} at #${it.adapterPosition}") } 40 | .onClick { activity.toast("Clicked #${it.adapterPosition}: ${it.binding.item}") } 41 | .onLongClick { activity.toast("Long-clicked #${it.adapterPosition}: ${it.binding.item}") } 42 | 43 | private val typePerson = Type(R.layout.item_person) 44 | .onCreate { println("Created ${it.binding.item} at #${it.adapterPosition}") } 45 | .onBind { println("Bound ${it.binding.item} at #${it.adapterPosition}") } 46 | .onBind { println("Recycled ${it.binding.item} at #${it.adapterPosition}") } 47 | .onClick { activity.toast("Clicked #${it.adapterPosition}: ${it.binding.item}") } 48 | .onLongClick { activity.toast("Long-clicked #${it.adapterPosition}: ${it.binding.item}") } 49 | 50 | 51 | override fun onActivityCreated(savedInstanceState: Bundle?) { 52 | super.onActivityCreated(savedInstanceState) 53 | val items = Data.items 54 | val stableIds = items == StableData.items 55 | 56 | //setMapAdapter(items, stableIds) 57 | //setMapAdapterWithListeners(items, stableIds) 58 | //setLayoutHandlerAdapter(items, stableIds) 59 | setTypeHandlerAdapter(items, stableIds) 60 | } 61 | 62 | private fun setMapAdapter(items: List, stableIds: Boolean) { 63 | LastAdapter(items, BR.item, stableIds) 64 | .map(R.layout.item_person) 65 | .map(R.layout.item_car) 66 | .map
(R.layout.item_header) 67 | .map(R.layout.item_point) 68 | .into(list) 69 | } 70 | 71 | private fun setMapAdapterWithListeners(items: List, stableIds: Boolean) { 72 | list.adapter = LastAdapter(items, BR.item, stableIds) 73 | .map(R.layout.item_header) 74 | .map(typePoint) 75 | .map(Type(R.layout.item_car) 76 | .onCreate { println("Created ${it.binding.item} at #${it.adapterPosition}") } 77 | .onBind { println("Bound ${it.binding.item} at #${it.adapterPosition}") } 78 | .onRecycle { println("Recycled ${it.binding.item} at #${it.adapterPosition}") } 79 | .onClick { activity.toast("Clicked #${it.adapterPosition}: ${it.binding.item}") } 80 | .onLongClick { activity.toast("Long-clicked #${it.adapterPosition}: ${it.binding.item}") } 81 | ) 82 | .map(R.layout.item_person) { 83 | onCreate { println("Created ${it.binding.item} at #${it.adapterPosition}") } 84 | onBind { println("Bound ${it.binding.item} at #${it.adapterPosition}") } 85 | onRecycle { println("Recycled ${it.binding.item} at #${it.adapterPosition}") } 86 | onClick { activity.toast("Clicked #${it.adapterPosition}: ${it.binding.item}") } 87 | onLongClick { activity.toast("Long-clicked #${it.adapterPosition}: ${it.binding.item}") } 88 | } 89 | .into(list) 90 | } 91 | 92 | private fun setLayoutHandlerAdapter(items: List, stableIds: Boolean) { 93 | LastAdapter(items, BR.item, stableIds).layout { item, position -> 94 | when (item) { 95 | is Header -> if (position == 0) R.layout.item_header_first else R.layout.item_header 96 | is Person -> R.layout.item_person 97 | is Point -> R.layout.item_point 98 | is Car -> R.layout.item_car 99 | else -> -1 100 | } 101 | }.into(list) 102 | } 103 | 104 | private fun setTypeHandlerAdapter(items: List, stableIds: Boolean) { 105 | LastAdapter(items, BR.item, stableIds).type { item, position -> 106 | when (item) { 107 | is Header -> if (position == 0) typeHeaderFirst else typeHeader 108 | is Point -> typePoint 109 | is Person -> typePerson 110 | is Car -> typeCar 111 | else -> null 112 | } 113 | }.into(list) 114 | } 115 | 116 | private fun Context?.toast(text: String) = this?.let { Toast.makeText(it, text, Toast.LENGTH_SHORT).show() } 117 | 118 | } 119 | -------------------------------------------------------------------------------- /app/src/main/java/com/github/nitrico/lastadapter_sample/ui/ListFragment.kt: -------------------------------------------------------------------------------- 1 | package com.github.nitrico.lastadapter_sample.ui 2 | 3 | import android.os.Bundle 4 | import android.support.v4.app.Fragment 5 | import android.support.v7.widget.LinearLayoutManager 6 | import android.support.v7.widget.RecyclerView 7 | import android.view.LayoutInflater 8 | import android.view.View 9 | import android.view.ViewGroup 10 | import com.github.nitrico.lastadapter_sample.R 11 | 12 | open class ListFragment : Fragment() { 13 | 14 | protected lateinit var list: RecyclerView 15 | 16 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { 17 | return inflater.inflate(R.layout.fragment_list, container, false) 18 | } 19 | 20 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 21 | super.onViewCreated(view, savedInstanceState) 22 | list = view.findViewById(R.id.list) 23 | } 24 | 25 | override fun onActivityCreated(savedInstanceState: Bundle?) { 26 | super.onActivityCreated(savedInstanceState) 27 | list.layoutManager = LinearLayoutManager(activity) 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /app/src/main/java/com/github/nitrico/lastadapter_sample/ui/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.github.nitrico.lastadapter_sample.ui 2 | 3 | import android.support.v7.app.AppCompatActivity 4 | import android.os.Bundle 5 | import android.support.v4.app.FragmentManager 6 | import android.support.v4.app.FragmentPagerAdapter 7 | import android.view.Menu 8 | import android.view.MenuItem 9 | import com.github.nitrico.lastadapter_sample.data.Data 10 | import com.github.nitrico.lastadapter_sample.R 11 | import com.github.nitrico.lastadapter_sample.data.Header 12 | import kotlinx.android.synthetic.main.activity_main.* 13 | import java.util.* 14 | 15 | class MainActivity : AppCompatActivity() { 16 | 17 | private val random = Random() 18 | 19 | private var randomPosition: Int = 0 20 | get() = random.nextInt(Data.items.size-1) 21 | 22 | override fun onCreate(savedInstanceState: Bundle?) { 23 | super.onCreate(savedInstanceState) 24 | setContentView(R.layout.activity_main) 25 | setSupportActionBar(toolbar) 26 | pager.adapter = ViewPagerAdapter(supportFragmentManager) 27 | tabs.setupWithViewPager(pager) 28 | } 29 | 30 | override fun onCreateOptionsMenu(menu: Menu) = consume { menuInflater.inflate(R.menu.main, menu) } 31 | 32 | override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { 33 | R.id.addFirst -> consume { 34 | Data.items.add(0, Header("New Header")) 35 | } 36 | R.id.addLast -> consume { 37 | Data.items.add(Data.items.size, Header("New header")) 38 | } 39 | R.id.addRandom -> consume { 40 | Data.items.add(randomPosition, Header("New Header")) 41 | } 42 | R.id.removeFirst -> consume { 43 | if (Data.items.isNotEmpty()) Data.items.removeAt(0) 44 | } 45 | R.id.removeLast -> consume { 46 | if (Data.items.isNotEmpty()) Data.items.removeAt(Data.items.size-1) 47 | } 48 | R.id.removeRandom -> consume { 49 | if (Data.items.isNotEmpty()) Data.items.removeAt(randomPosition) 50 | } 51 | else -> super.onOptionsItemSelected(item) 52 | } 53 | 54 | private fun consume(f: () -> Unit): Boolean { 55 | f() 56 | return true 57 | } 58 | 59 | class ViewPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) { 60 | override fun getCount() = 2 61 | override fun getItem(i: Int) = if (i == 0) KotlinListFragment() else JavaListFragment() 62 | override fun getPageTitle(i: Int) = if (i == 0) "Kotlin" else "Java" 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 12 | 13 | 18 | 19 | 23 | 24 | 25 | 26 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /app/src/main/res/layout/fragment_list.xml: -------------------------------------------------------------------------------- 1 | 9 | -------------------------------------------------------------------------------- /app/src/main/res/layout/item_car.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 10 | 15 | 16 | 21 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /app/src/main/res/layout/item_header.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | 12 | 13 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /app/src/main/res/layout/item_header_first.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | 12 | 13 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /app/src/main/res/layout/item_person.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | 14 | 15 | 20 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /app/src/main/res/layout/item_point.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | 14 | 15 | 20 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /app/src/main/res/menu/main.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 9 | 13 | 14 | 18 | 19 | 23 | 24 | 28 | 29 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nitrico/LastAdapter/b19d66fb078d345be7a4cdbe5d8c4f30cb72d68a/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nitrico/LastAdapter/b19d66fb078d345be7a4cdbe5d8c4f30cb72d68a/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nitrico/LastAdapter/b19d66fb078d345be7a4cdbe5d8c4f30cb72d68a/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nitrico/LastAdapter/b19d66fb078d345be7a4cdbe5d8c4f30cb72d68a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nitrico/LastAdapter/b19d66fb078d345be7a4cdbe5d8c4f30cb72d68a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #607D8B 4 | #455A64 5 | #FFC107 6 | 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | LastAdapter 4 | 5 | Add first 6 | Add last 7 | Add random 8 | 9 | Remove first 10 | Remove last 11 | Remove random 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext.versions = [ 3 | sdkMin : 14, 4 | sdkTarget : 27, 5 | buildTools : '27.0.1', 6 | gradlePlugin : '3.0.1', 7 | kotlin : '1.2.0', 8 | support : '27.0.2' 9 | ] 10 | repositories { 11 | google() 12 | jcenter() 13 | mavenCentral() 14 | } 15 | dependencies { 16 | classpath "com.android.tools.build:gradle:$versions.gradlePlugin" 17 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$versions.kotlin" 18 | classpath "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.0" 19 | classpath "com.github.dcendents:android-maven-gradle-plugin:2.0" 20 | } 21 | } 22 | 23 | allprojects { 24 | repositories { 25 | google() 26 | jcenter() 27 | } 28 | } 29 | 30 | task clean(type: Delete) { 31 | delete rootProject.buildDir 32 | } 33 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | org.gradle.jvmargs=-Xmx2048m 21 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nitrico/LastAdapter/b19d66fb078d345be7a4cdbe5d8c4f30cb72d68a/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed May 17 23:59:27 CEST 2017 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-4.3.1-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\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /lastadapter/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /lastadapter/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.library' 3 | id 'kotlin-android' 4 | } 5 | 6 | android { 7 | compileSdkVersion versions.sdkTarget 8 | buildToolsVersion versions.buildTools 9 | defaultConfig.minSdkVersion versions.sdkMin 10 | dataBinding.enabled true 11 | } 12 | 13 | dependencies { 14 | compile "com.android.support:recyclerview-v7:$versions.support" 15 | compile "org.jetbrains.kotlin:kotlin-stdlib:$versions.kotlin" 16 | } 17 | 18 | apply from: 'publish.gradle' 19 | -------------------------------------------------------------------------------- /lastadapter/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in C:\Android\SDK/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /lastadapter/publish.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.github.dcendents.android-maven' 2 | apply plugin: 'com.jfrog.bintray' 3 | 4 | def libName = 'lastadapter' 5 | def libGroup = 'com.github.nitrico.' + libName 6 | def libSite = 'https://github.com/nitrico/' + libName 7 | def libGit = libSite + '.git' 8 | def libTracker = libSite + '/issues' 9 | def libDesc = "Don't write any other RecyclerView adapter again. Not even a Holder!" 10 | def libTags = ['android', 'recyclerview', 'adapter', 'data binding', 'kotlin'] 11 | 12 | group libGroup 13 | version '2.3.0' 14 | 15 | Properties properties = new Properties() 16 | properties.load(rootProject.file('local.properties').newDataInputStream()) 17 | 18 | bintray { 19 | user properties.getProperty('bintray_user') 20 | key properties.getProperty('bintray_key') 21 | configurations = ['archives'] 22 | pkg { 23 | repo = 'maven' 24 | name = libName 25 | desc = libDesc 26 | websiteUrl = libSite 27 | issueTrackerUrl = libTracker 28 | vcsUrl = libGit 29 | labels = libTags 30 | licenses = ['Apache-2.0'] 31 | publish = true 32 | publicDownloadNumbers = true 33 | } 34 | } 35 | 36 | install { 37 | repositories.mavenInstaller { 38 | pom.project { 39 | packaging 'aar' 40 | groupId libGroup 41 | artifactId libName 42 | name libName 43 | description libDesc 44 | url libSite 45 | licenses { 46 | license { 47 | name 'The Apache Software License, Version 2.0' 48 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 49 | } 50 | } 51 | developers { 52 | developer { 53 | id 'moreno' 54 | name 'Miguel Ángel Moreno' 55 | email 'nitrico@gmail.com' 56 | } 57 | } 58 | scm { 59 | connection libGit 60 | developerConnection libGit 61 | url libSite 62 | } 63 | } 64 | } 65 | } 66 | 67 | task sourcesJar(type: Jar) { 68 | from android.sourceSets.main.java.srcDirs 69 | classifier 'sources' 70 | } 71 | 72 | artifacts { 73 | archives sourcesJar 74 | } 75 | -------------------------------------------------------------------------------- /lastadapter/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /lastadapter/src/main/java/com/github/nitrico/lastadapter/Holder.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Miguel Ángel Moreno 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 | package com.github.nitrico.lastadapter 18 | 19 | import android.databinding.ViewDataBinding 20 | import android.support.v7.widget.RecyclerView 21 | 22 | open class Holder(val binding: B) : RecyclerView.ViewHolder(binding.root) { 23 | internal var created = false 24 | } 25 | -------------------------------------------------------------------------------- /lastadapter/src/main/java/com/github/nitrico/lastadapter/Interfaces.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Miguel Ángel Moreno 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 | package com.github.nitrico.lastadapter 18 | 19 | interface Handler 20 | 21 | interface TypeHandler : Handler { 22 | fun getItemType(item: Any, position: Int): BaseType? 23 | } 24 | 25 | interface LayoutHandler : Handler { 26 | fun getItemLayout(item: Any, position: Int): Int 27 | } 28 | 29 | interface StableId { 30 | val stableId: Long 31 | } 32 | -------------------------------------------------------------------------------- /lastadapter/src/main/java/com/github/nitrico/lastadapter/LastAdapter.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Miguel Ángel Moreno 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 | package com.github.nitrico.lastadapter 18 | 19 | import android.databinding.DataBindingUtil 20 | import android.databinding.ObservableList 21 | import android.databinding.OnRebindCallback 22 | import android.databinding.ViewDataBinding 23 | import android.support.v7.widget.RecyclerView 24 | import android.view.LayoutInflater 25 | import android.view.ViewGroup 26 | 27 | class LastAdapter(private val list: List, 28 | private val variable: Int? = null, 29 | stableIds: Boolean = false) : RecyclerView.Adapter>() { 30 | 31 | constructor(list: List) : this(list, null, false) 32 | constructor(list: List, variable: Int) : this(list, variable, false) 33 | constructor(list: List, stableIds: Boolean) : this(list, null, stableIds) 34 | 35 | private val DATA_INVALIDATION = Any() 36 | private val callback = ObservableListCallback(this) 37 | private var recyclerView: RecyclerView? = null 38 | private var inflater: LayoutInflater? = null 39 | 40 | private val map = mutableMapOf, BaseType>() 41 | private var layoutHandler: LayoutHandler? = null 42 | private var typeHandler: TypeHandler? = null 43 | 44 | init { 45 | setHasStableIds(stableIds) 46 | } 47 | 48 | @JvmOverloads 49 | fun map(clazz: Class, layout: Int, variable: Int? = null) 50 | = apply { map[clazz] = BaseType(layout, variable) } 51 | 52 | inline fun map(layout: Int, variable: Int? = null) 53 | = map(T::class.java, layout, variable) 54 | 55 | fun map(clazz: Class, type: AbsType<*>) 56 | = apply { map[clazz] = type } 57 | 58 | inline fun map(type: AbsType<*>) 59 | = map(T::class.java, type) 60 | 61 | inline fun map(layout: Int, 62 | variable: Int? = null, 63 | noinline f: (Type.() -> Unit)? = null) 64 | = map(T::class.java, Type(layout, variable).apply { f?.invoke(this) }) 65 | 66 | fun handler(handler: Handler) = apply { 67 | when (handler) { 68 | is LayoutHandler -> { 69 | if (variable == null) { 70 | throw IllegalStateException("No variable specified in LastAdapter constructor") 71 | } 72 | layoutHandler = handler 73 | } 74 | is TypeHandler -> typeHandler = handler 75 | } 76 | } 77 | 78 | inline fun layout(crossinline f: (Any, Int) -> Int) = handler(object : LayoutHandler { 79 | override fun getItemLayout(item: Any, position: Int) = f(item, position) 80 | }) 81 | 82 | inline fun type(crossinline f: (Any, Int) -> AbsType<*>?) = handler(object : TypeHandler { 83 | override fun getItemType(item: Any, position: Int) = f(item, position) 84 | }) 85 | 86 | fun into(recyclerView: RecyclerView) = apply { recyclerView.adapter = this } 87 | 88 | 89 | 90 | override fun onCreateViewHolder(view: ViewGroup, viewType: Int): Holder { 91 | val binding = DataBindingUtil.inflate(inflater, viewType, view, false) 92 | val holder = Holder(binding) 93 | binding.addOnRebindCallback(object : OnRebindCallback() { 94 | override fun onPreBind(binding: ViewDataBinding) = recyclerView?.isComputingLayout ?: false 95 | override fun onCanceled(binding: ViewDataBinding) { 96 | if (recyclerView?.isComputingLayout ?: true) { 97 | return 98 | } 99 | val position = holder.adapterPosition 100 | if (position != RecyclerView.NO_POSITION) { 101 | notifyItemChanged(position, DATA_INVALIDATION) 102 | } 103 | } 104 | }) 105 | return holder 106 | } 107 | 108 | override fun onBindViewHolder(holder: Holder, position: Int) { 109 | val type = getType(position)!! 110 | holder.binding.setVariable(getVariable(type), list[position]) 111 | holder.binding.executePendingBindings() 112 | @Suppress("UNCHECKED_CAST") 113 | if (type is AbsType<*>) { 114 | if (!holder.created) { 115 | notifyCreate(holder, type as AbsType) 116 | } 117 | notifyBind(holder, type as AbsType) 118 | } 119 | } 120 | 121 | override fun onBindViewHolder(holder: Holder, position: Int, payloads: List) { 122 | if (isForDataBinding(payloads)) { 123 | holder.binding.executePendingBindings() 124 | } else { 125 | super.onBindViewHolder(holder, position, payloads) 126 | } 127 | } 128 | 129 | override fun onViewRecycled(holder: Holder) { 130 | val position = holder.adapterPosition 131 | if (position != RecyclerView.NO_POSITION && position < list.size) { 132 | val type = getType(position)!! 133 | if (type is AbsType<*>) { 134 | @Suppress("UNCHECKED_CAST") 135 | notifyRecycle(holder, type as AbsType) 136 | } 137 | } 138 | } 139 | 140 | override fun getItemId(position: Int): Long { 141 | if (hasStableIds()) { 142 | val item = list[position] 143 | if (item is StableId) { 144 | return item.stableId 145 | } else { 146 | throw IllegalStateException("${item.javaClass.simpleName} must implement StableId interface.") 147 | } 148 | } else { 149 | return super.getItemId(position) 150 | } 151 | } 152 | 153 | override fun getItemCount() = list.size 154 | 155 | override fun onAttachedToRecyclerView(rv: RecyclerView) { 156 | if (recyclerView == null && list is ObservableList) { 157 | list.addOnListChangedCallback(callback) 158 | } 159 | recyclerView = rv 160 | inflater = LayoutInflater.from(rv.context) 161 | } 162 | 163 | override fun onDetachedFromRecyclerView(rv: RecyclerView) { 164 | if (recyclerView != null && list is ObservableList) { 165 | list.removeOnListChangedCallback(callback) 166 | } 167 | recyclerView = null 168 | } 169 | 170 | override fun getItemViewType(position: Int) 171 | = layoutHandler?.getItemLayout(list[position], position) 172 | ?: typeHandler?.getItemType(list[position], position)?.layout 173 | ?: getType(position)?.layout 174 | ?: throw RuntimeException("Invalid object at position $position: ${list[position].javaClass}") 175 | 176 | private fun getType(position: Int) 177 | = typeHandler?.getItemType(list[position], position) 178 | ?: map[list[position].javaClass] 179 | 180 | private fun getVariable(type: BaseType) 181 | = type.variable 182 | ?: variable 183 | ?: throw IllegalStateException("No variable specified for type ${type.javaClass.simpleName}") 184 | 185 | private fun isForDataBinding(payloads: List): Boolean { 186 | if (payloads.isEmpty()) { 187 | return false 188 | } 189 | payloads.forEach { 190 | if (it != DATA_INVALIDATION) { 191 | return false 192 | } 193 | } 194 | return true 195 | } 196 | 197 | private fun notifyCreate(holder: Holder, type: AbsType) { 198 | when (type) { 199 | is Type -> { 200 | setClickListeners(holder, type) 201 | type.onCreate?.invoke(holder) 202 | } 203 | is ItemType -> type.onCreate(holder) 204 | } 205 | holder.created = true 206 | } 207 | 208 | private fun notifyBind(holder: Holder, type: AbsType) { 209 | when (type) { 210 | is Type -> type.onBind?.invoke(holder) 211 | is ItemType -> type.onBind(holder) 212 | } 213 | } 214 | 215 | private fun notifyRecycle(holder: Holder, type: AbsType) { 216 | when (type) { 217 | is Type -> type.onRecycle?.invoke(holder) 218 | is ItemType -> type.onRecycle(holder) 219 | } 220 | } 221 | 222 | private fun setClickListeners(holder: Holder, type: Type) { 223 | val onClick = type.onClick 224 | if (onClick != null) { 225 | holder.itemView.setOnClickListener { 226 | onClick(holder) 227 | } 228 | } 229 | val onLongClick = type.onLongClick 230 | if (onLongClick != null) { 231 | holder.itemView.setOnLongClickListener { 232 | onLongClick(holder) 233 | true 234 | } 235 | } 236 | } 237 | 238 | } 239 | -------------------------------------------------------------------------------- /lastadapter/src/main/java/com/github/nitrico/lastadapter/ObservableListCallback.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Miguel Ángel Moreno 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 | package com.github.nitrico.lastadapter 18 | 19 | import android.databinding.ObservableList 20 | import android.os.Looper 21 | import android.support.v7.widget.RecyclerView 22 | import java.lang.ref.WeakReference 23 | 24 | class ObservableListCallback(adapter: RecyclerView.Adapter) 25 | : ObservableList.OnListChangedCallback>() { 26 | 27 | private val reference = WeakReference>(adapter) 28 | private val adapter: RecyclerView.Adapter? 29 | get() { 30 | if (Thread.currentThread() == Looper.getMainLooper().thread) return reference.get() 31 | else throw IllegalStateException("You must modify the ObservableList on the main thread") 32 | } 33 | 34 | override fun onChanged(list: ObservableList) { 35 | adapter?.notifyDataSetChanged() 36 | } 37 | 38 | override fun onItemRangeChanged(list: ObservableList, from: Int, count: Int) { 39 | adapter?.notifyItemRangeChanged(from, count) 40 | } 41 | 42 | override fun onItemRangeInserted(list: ObservableList, from: Int, count: Int) { 43 | adapter?.notifyItemRangeInserted(from, count) 44 | } 45 | 46 | override fun onItemRangeRemoved(list: ObservableList, from: Int, count: Int) { 47 | adapter?.notifyItemRangeRemoved(from, count) 48 | } 49 | 50 | override fun onItemRangeMoved(list: ObservableList, from: Int, to: Int, count: Int) { 51 | adapter?.let { for (i in 0..count-1) it.notifyItemMoved(from+i, to+i) } 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /lastadapter/src/main/java/com/github/nitrico/lastadapter/Types.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Miguel Ángel Moreno 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 | package com.github.nitrico.lastadapter 18 | 19 | import android.databinding.ViewDataBinding 20 | 21 | open class BaseType 22 | @JvmOverloads constructor(open val layout: Int, open val variable: Int? = null) 23 | 24 | @Suppress("unused") 25 | abstract class AbsType 26 | @JvmOverloads constructor(layout: Int, variable: Int? = null) : BaseType(layout, variable) 27 | 28 | open class ItemType 29 | @JvmOverloads constructor(layout: Int, variable: Int? = null) : AbsType(layout, variable) { 30 | open fun onCreate(holder: Holder) { } 31 | open fun onBind(holder: Holder) { } 32 | open fun onRecycle(holder: Holder) { } 33 | } 34 | 35 | open class Type 36 | @JvmOverloads constructor(layout: Int, variable: Int? = null) : AbsType(layout, variable) { 37 | internal var onCreate: Action? = null; private set 38 | internal var onBind: Action? = null; private set 39 | internal var onClick: Action? = null; private set 40 | internal var onLongClick: Action? = null; private set 41 | internal var onRecycle: Action? = null; private set 42 | fun onCreate(action: Action?) = apply { onCreate = action } 43 | fun onBind(action: Action?) = apply { onBind = action } 44 | fun onClick(action: Action?) = apply { onClick = action } 45 | fun onLongClick(action: Action?) = apply { onLongClick = action } 46 | fun onRecycle(action: Action?) = apply { onRecycle = action } 47 | } 48 | 49 | typealias Action = (Holder) -> Unit 50 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':lastadapter' 2 | --------------------------------------------------------------------------------