├── .buildscript └── deploy_snapshot.sh ├── .circleci └── config.yml ├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── LICENSE ├── README.md ├── _config.yml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── library ├── .gitignore ├── build.gradle └── src │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── com │ │ └── link184 │ │ └── kidadapter │ │ ├── Annotations.kt │ │ ├── ContextDsl.kt │ │ ├── Extensions.kt │ │ ├── base │ │ ├── BaseAdapter.kt │ │ ├── BaseViewHolder.kt │ │ ├── KidDiffUtilCallback.kt │ │ └── KidList.kt │ │ ├── exceptions │ │ └── KidExceptions.kt │ │ ├── simple │ │ ├── SingleKidAdapter.kt │ │ └── SingleKidAdapterConfiguration.kt │ │ └── typed │ │ ├── AdapterViewType.kt │ │ ├── AdapterViewTypeConfiguration.kt │ │ ├── TypedKidAdapter.kt │ │ ├── TypedKidAdapterConfiguration.kt │ │ ├── restructure │ │ ├── RestructureConfiguration.kt │ │ ├── RestructureItem.kt │ │ └── RestructureType.kt │ │ └── update │ │ ├── UpdateConfiguration.kt │ │ ├── UpdateItem.kt │ │ └── UpdateType.kt │ └── test │ ├── java │ └── com │ │ └── link184 │ │ └── kidadapter │ │ ├── ErrorCasesTest.kt │ │ ├── MockUtils.kt │ │ ├── MultiAdapterTest.kt │ │ ├── RecyclerViewActivity.kt │ │ ├── RestructureTest.kt │ │ └── SingleKidAdapterTest.kt │ └── resources │ └── mockito-extensions │ └── org.mockito.plugins.MockMaker ├── logo.png ├── publish.gradle ├── sample ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── link184 │ │ └── sample │ │ ├── MainActivity.kt │ │ ├── MultiTypeActivity.kt │ │ ├── MultiTypeWithTagsActivity.kt │ │ ├── SingleTypeActivity.kt │ │ └── ViewPagerActivity.kt │ └── res │ ├── anim │ ├── item_fall_down_high.xml │ ├── item_fall_down_low.xml │ ├── item_fall_down_medium.xml │ ├── item_rise_up_high.xml │ ├── item_rise_up_medium.xml │ ├── item_scale_up_rotation_medium.xml │ ├── item_slide_right_high.xml │ ├── item_slide_right_medium.xml │ ├── layout_fall_down_high.xml │ ├── layout_fall_down_low.xml │ ├── layout_fall_down_medium.xml │ ├── layout_rise_up_high.xml │ ├── layout_rise_up_medium.xml │ ├── layout_scale_up_rotation_medium.xml │ ├── layout_slide_right_high.xml │ └── layout_slide_right_medium.xml │ ├── drawable-v24 │ └── ic_launcher_foreground.xml │ ├── drawable │ └── ic_launcher_background.xml │ ├── layout │ ├── activity_main.xml │ ├── activity_multi_type.xml │ ├── activity_multi_type_with_tags.xml │ ├── activity_single_type.xml │ ├── activity_view_pager.xml │ ├── item_int.xml │ ├── item_text.xml │ └── view_tab.xml │ ├── mipmap-anydpi-v26 │ ├── ic_launcher.xml │ └── ic_launcher_round.xml │ ├── mipmap-hdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-mdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ └── values │ ├── colors.xml │ ├── integers.xml │ ├── strings.xml │ └── styles.xml └── settings.gradle /.buildscript/deploy_snapshot.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Deploy a jar, source jar, and javadoc jar to Sonatype's snapshot repo. 4 | # 5 | # Adapted from https://coderwall.com/p/9b_lfq and 6 | # http://benlimmer.com/2013/12/26/automatically-publish-javadoc-to-gh-pages-with-travis-ci/ 7 | 8 | SLUG="Link184/KidAdapter" 9 | JDK="oraclejdk8" 10 | BRANCH="master" 11 | 12 | set -e 13 | 14 | if [ "$TRAVIS_REPO_SLUG" != "$SLUG" ]; then 15 | echo "Skipping snapshot deployment: wrong repository. Expected '$SLUG' but was '$TRAVIS_REPO_SLUG'." 16 | elif [ "$TRAVIS_JDK_VERSION" != "$JDK" ]; then 17 | echo "Skipping snapshot deployment: wrong JDK. Expected '$JDK' but was '$TRAVIS_JDK_VERSION'." 18 | elif [ "$TRAVIS_PULL_REQUEST" != "false" ]; then 19 | echo "Skipping snapshot deployment: was pull request." 20 | elif [ "$TRAVIS_BRANCH" != "$BRANCH" ]; then 21 | echo "Skipping snapshot deployment: wrong branch. Expected '$BRANCH' but was '$TRAVIS_BRANCH'." 22 | else 23 | echo "Deploying snapshot..." 24 | ./gradlew uploadArchives 25 | echo "Snapshot deployed!" 26 | fi 27 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Use the latest 2.1 version of CircleCI pipeline process engine. 2 | # See: https://circleci.com/docs/2.0/configuration-reference 3 | # For a detailed guide to building and testing on Android, read the docs: 4 | # https://circleci.com/docs/2.0/language-android/ for more details. 5 | version: 2.1 6 | 7 | # Orbs are reusable packages of CircleCI configuration that you may share across projects, enabling you to create encapsulated, parameterized commands, jobs, and executors that can be used across multiple projects. 8 | # See: https://circleci.com/docs/2.0/orb-intro/ 9 | orbs: 10 | android: circleci/android@1.0.3 11 | 12 | # Define a job to be invoked later in a workflow. 13 | # See: https://circleci.com/docs/2.0/configuration-reference/#jobs 14 | jobs: 15 | # Below is the definition of your job to build and test your app, you can rename and customize it as you want. 16 | build-and-test: 17 | # These next lines define the Android machine image executor. 18 | # See: https://circleci.com/docs/2.0/executor-types/ 19 | executor: 20 | name: android/android-machine 21 | 22 | # Add steps to the job 23 | # See: https://circleci.com/docs/2.0/configuration-reference/#steps 24 | steps: 25 | # Checkout the code as the first step. 26 | - checkout 27 | 28 | # The next step will run the unit tests 29 | - android/run-tests: 30 | test-command: ./gradlew lint testDebug --continue 31 | 32 | # Then start the emulator and run the Instrumentation tests! 33 | - android/start-emulator-and-run-tests: 34 | test-command: ./gradlew connectedDebugAndroidTest 35 | system-image: system-images;android-25;google_apis;x86 36 | 37 | # And finally run the release build 38 | - run: 39 | name: Run tests 40 | command: | 41 | ./gradlew assembleRelease 42 | 43 | # Invoke jobs via workflows 44 | # See: https://circleci.com/docs/2.0/configuration-reference/#workflows 45 | workflows: 46 | sample: # This is the name of the workflow, feel free to change it to better match your workflow. 47 | # Inside the workflow, you define the jobs you want to run. 48 | jobs: 49 | - build-and-test 50 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "[BUG]" 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: "[FEATURE]" 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | /captures 8 | .externalNativeBuild 9 | gradle.properties -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | ![logo](https://github.com/Link184/KidAdapter/blob/master/logo.png) 3 | 4 | # KidAdapter 5 | RecyclerView adapter for kids. 6 | 7 | A kotlin dsl mechanism to simplify and reduce boilerplate logic of a `RecyclerView.Adapter`. 8 | 9 | With KidAdapter you can use all power of kotlin dsl to avoid wired standard implementation of `RecyclerView.Adapter` 10 | view types. You can easily maintain, update, move, swap, remove or add new view types using dsl code blocks. 11 | 12 | Bonus: Almost all logic by default works with `DiffUtil` 13 | 14 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.link184/kid-adapter/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.link184/kid-adapter) 15 | [![CircleCI](https://circleci.com/gh/Link184/KidAdapter/tree/master.svg?style=svg)](https://circleci.com/gh/Link184/KidAdapter/tree/master) 16 | [![ktlint](https://img.shields.io/badge/code%20style-%E2%9D%A4-FF4081.svg)](https://ktlint.github.io/) 17 | [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-KidAdapter-brightgreen.svg?style=flat)](https://android-arsenal.com/details/1/7397) 18 | 19 | 20 | Gradle 21 | -------- 22 | 23 | Gradle: 24 | 25 | ```gradle 26 | implementation 'com.link184:kid-adapter:1.4.1' 27 | ``` 28 | 29 | Samples 30 | ----- 31 | 32 | Simple adapter without view types: 33 | ```kotlin 34 | val adapter = recyclerView.setUp { //an extension on RecyclerView which return a instance of adapter 35 | // optional, set layout manager or leave to use default linear vertical 36 | withLayoutManager(GridLayoutManager(context, 3)) 37 | // set layout res id for each adapter item 38 | withLayoutResId(R.layout.item_text) 39 | // set adapter items 40 | withItems(mutableListOf(MyObject(name = "one"), MyObject("two"), MyObject("three"))) 41 | // set bind action 42 | bind { item -> // this - adapter view holder itemView, item - current item 43 | this.setBackgroundColor(getRandomColor()) 44 | stringName.text = item.name //string view is a synthetic inflated view from bind function context 45 | setOnClickListener { ... } //click listener on ViewHolder.itemView 46 | } 47 | // if you need adapter position use this method instead of "bind" 48 | bindIndexed { item, index -> // item - current item, index - adapterPosition 49 | ... 50 | } 51 | } 52 | 53 | //runtime adapter update 54 | adapter + MyObject("four") 55 | adapter += mutableListOf(MyObject("1"), MyObject("2")) 56 | adapter[2] = MyObject("two") 57 | adapter - MyObject("four") 58 | adapter + MyObject("five") + MyObject("six") - MyObject("one") 59 | ``` 60 | 61 | Adapter with view types: 62 | ```kotlin 63 | val adapter = recyclerView.setUp { 64 | // declare a viewtype 65 | withViewType("FIRST_STRING_TAG") { // tag is optional but is useful for future updates when you have multiple view typs with the same item types 66 | // optional, set layout manager or leave to use default linear vertical 67 | withLayoutManager { GridLayoutManager(context, 3) } 68 | // set layout res id to current view type 69 | withLayoutResId(R.layout.item_text) 70 | // set items to currect view type 71 | withItems(mutableListOf("one", "two", "three", "four", "five", "six", "seven")) 72 | // optional, a callback from DiffUtils, by default it compare items with equals() method, set it if you need a custom behavior 73 | withContentComparator { oldItem, newItem -> 74 | oldItem.length > newItem.length 75 | } 76 | // optional, a callback from DiffUtils, by default it compare items with equals() method, set it if you need a custom behavior 77 | withItemsComparator { oldItem, newItem -> 78 | oldItem.hashCode() == newItem.hashCode() 79 | } 80 | // set bind action 81 | bind { // this - is adapter view hoder itemView, item - current item 82 | stringName.text = it 83 | setOnClickListener { ... } //click listener on ViewHolder.itemView 84 | } 85 | // if you need adapter position use this method instead of "bind" 86 | bindIndexed { item, index -> // item - current item, index - adapterPosition 87 | ... 88 | } 89 | } 90 | 91 | withViewType { 92 | withLayoutResId(R.layout.item_int) 93 | withItems(mutableListOf(1, 2, 3, 4, 5, 6)) 94 | bind { 95 | intName.text = it.toString() 96 | } 97 | } 98 | 99 | 100 | withViewType("SECOND_STRING_TAG") { 101 | withLayoutResId(R.layout.item_text) 102 | withItems(mutableListOf("eight", "nine", "ten", "eleven", "twelve")) 103 | bind { 104 | stringName.text = it 105 | } 106 | } 107 | 108 | //Update adapter as needed 109 | adapter update { ... } 110 | } 111 | ``` 112 | 113 | Update multiple view type adapter. 114 | 115 | ```kotlin 116 | adapter update { 117 | insertBottom(mutableListOf("thirteen", "fourteen"), SECOND_STRING_TAG) 118 | insertTop(mutableListOf("asd", "asd")) // there are no tag, library automatically detect and insert items on first list of strings 119 | insert(2, mutableListOf(4, 5, 6, 7)) // no tag, items will be inserted in first list of integers 120 | removeItems(mutableListOf(1,3,6)) 121 | removeItems(mutableListOf("one", "thirteen")) 122 | removeAll() 123 | } 124 | 125 | adapter restructure { 126 | insert(2, "tag") { 127 | withItems(items) 128 | withLayoutResId(android.R.layout.list_content) 129 | bind { 130 | println("We are here $it") 131 | } 132 | } 133 | insertTop("top1Tag") { ... } 134 | insert(3, "insertAt3Tag") { ... } 135 | insertBottom("bottom1Tag") { ... } 136 | replace("top1Tag") { ... } 137 | swap(0, 3) 138 | removeAll() 139 | insertTop("top1Tag") { ... } 140 | } 141 | ``` 142 | 143 | Proguard 144 | ------- 145 | Don't worry about that. 146 | 147 | License 148 | ------- 149 | See the [LICENSE][1] file for details. 150 | 151 | [1]: https://github.com/Link184/KidAdapter/blob/master/LICENSE 152 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-hacker -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext.kotlin_version = '1.9.20' 5 | repositories { 6 | mavenCentral() 7 | google() 8 | } 9 | dependencies { 10 | classpath 'com.android.tools.build:gradle:8.6.1' 11 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 12 | classpath "org.jetbrains.dokka:dokka-gradle-plugin:$kotlin_version" 13 | classpath "com.vanniktech:gradle-maven-publish-plugin:0.22.0" 14 | } 15 | } 16 | 17 | allprojects { 18 | repositories { 19 | mavenCentral() 20 | google() 21 | } 22 | } 23 | 24 | task clean(type: Delete) { 25 | delete rootProject.buildDir 26 | } 27 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx1536m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # Kotlin code style for this project: "official" or "obsolete": 15 | kotlin.code.style=official 16 | 17 | SONATYPE_HOST=DEFAULT 18 | RELEASE_SIGNING_ENABLED=true 19 | 20 | GROUP=com.link184 21 | POM_ARTIFACT_ID=kid-adapter 22 | VERSION_NAME=1.4.1-SNAPSHOT 23 | 24 | POM_NAME=Kid Adapter 25 | POM_DESCRIPTION=kotlin dsl for kids to simplify RecyclerView.Adapter logic 26 | 27 | POM_URL=https://github.com/Link184/KidAdapter 28 | POM_SCM_URL=https://github.com/Link184/KidAdapter 29 | POM_SCM_CONNECTION=scm:git:git://github.com/Link184/KidAdapter.git 30 | POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/Link184/KidAdapter.git 31 | 32 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 33 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 34 | POM_LICENCE_DIST=repo 35 | 36 | POM_DEVELOPER_ID=link184 37 | POM_DEVELOPER_NAME=Eugeniu Tufar 38 | android.useAndroidX=true 39 | android.enableJetifier=true 40 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Link184/KidAdapter/a922f8382f5b5957ddbf15a09f48c1d27b99b874/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Jul 09 20:05:12 WITA 2020 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-8.9-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /library/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /library/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | apply plugin: 'kotlin-android' 4 | apply plugin: 'org.jetbrains.dokka' 5 | apply plugin: 'com.vanniktech.maven.publish' 6 | 7 | android { 8 | compileSdk 35 9 | defaultConfig { 10 | minSdkVersion 19 11 | targetSdk 35 12 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 13 | } 14 | 15 | compileOptions { 16 | sourceCompatibility = JavaVersion.VERSION_1_8 17 | targetCompatibility = JavaVersion.VERSION_1_8 18 | } 19 | 20 | kotlinOptions { 21 | jvmTarget = "1.8" 22 | } 23 | 24 | testOptions { 25 | unitTests { 26 | includeAndroidResources = true 27 | } 28 | } 29 | namespace 'com.link184.kidadapter' 30 | } 31 | 32 | configurations { 33 | ktlint 34 | } 35 | 36 | task ktlint(type: JavaExec, group: "verification") { 37 | description = "Check Kotlin code style." 38 | classpath = configurations.ktlint 39 | main = "com.github.shyiko.ktlint.Main" 40 | args "src/**/*.kt" 41 | // to generate report in checkstyle format prepend following args: 42 | // "--reporter=plain", "--reporter=checkstyle,output=${buildDir}/ktlint.xml" 43 | // see https://github.com/shyiko/ktlint#usage for more 44 | } 45 | check.dependsOn ktlint 46 | 47 | task ktlintFormat(type: JavaExec, group: "formatting") { 48 | description = "Fix Kotlin code style deviations." 49 | classpath = configurations.ktlint 50 | main = "com.github.shyiko.ktlint.Main" 51 | args "-F", "src/**/*.kt" 52 | } 53 | 54 | dependencies { 55 | implementation fileTree(dir: 'libs', include: ['*.jar']) 56 | api 'androidx.recyclerview:recyclerview:1.3.2' 57 | api 'androidx.viewpager2:viewpager2:1.1.0' 58 | 59 | ktlint "com.github.shyiko:ktlint:0.29.0" 60 | 61 | testImplementation 'junit:junit:4.13.2' 62 | testImplementation 'org.robolectric:robolectric:4.13' 63 | testImplementation "org.jetbrains.kotlin:kotlin-test:$kotlin_version" 64 | testImplementation 'org.mockito:mockito-core:4.0.0' 65 | 66 | androidTestImplementation 'androidx.test:runner:1.6.2' 67 | } 68 | -------------------------------------------------------------------------------- /library/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/Annotations.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter 2 | 3 | @DslMarker 4 | @Target(AnnotationTarget.CLASS, AnnotationTarget.TYPEALIAS, AnnotationTarget.TYPE, AnnotationTarget.FUNCTION) 5 | internal annotation class BindDsl 6 | 7 | @DslMarker 8 | @Target(AnnotationTarget.CLASS, AnnotationTarget.TYPEALIAS, AnnotationTarget.TYPE, AnnotationTarget.FUNCTION) 9 | internal annotation class ConfigurationDsl 10 | 11 | @DslMarker 12 | @Target(AnnotationTarget.CLASS, AnnotationTarget.TYPEALIAS, AnnotationTarget.TYPE, AnnotationTarget.FUNCTION) 13 | internal annotation class ExtensionDsl -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/ContextDsl.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter 2 | 3 | /** 4 | * DslMarker for pipeline execution context 5 | */ 6 | @DslMarker 7 | @Target(AnnotationTarget.CLASS, AnnotationTarget.TYPEALIAS, AnnotationTarget.TYPE, AnnotationTarget.FUNCTION) 8 | annotation class ContextDsl -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/Extensions.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter 2 | 3 | import androidx.recyclerview.widget.LinearLayoutManager 4 | import androidx.recyclerview.widget.RecyclerView 5 | import androidx.viewpager2.widget.ViewPager2 6 | import com.link184.kidadapter.simple.SingleKidAdapter 7 | import com.link184.kidadapter.simple.SingleKidAdapterConfiguration 8 | import com.link184.kidadapter.typed.TypedKidAdapter 9 | import com.link184.kidadapter.typed.TypedKidAdapterConfiguration 10 | 11 | /** 12 | * Simple way to create [RecyclerView.Adapter] with no view types 13 | * @param block hare adapter can be configured 14 | * @param T adapter item models type. 15 | * @receiver any instance of [RecyclerView] 16 | * @return a child instance of a [RecyclerView.Adapter] 17 | */ 18 | fun RecyclerView.setUp(block: SingleKidAdapterConfiguration.() -> Unit): SingleKidAdapter { 19 | val configuration = SingleKidAdapterConfiguration().apply(block) 20 | return SingleKidAdapter.create(block).apply { 21 | if (layoutManager == null) { 22 | layoutManager = configuration.layoutManager ?: LinearLayoutManager(context) 23 | } 24 | configuration.decorator?.let { 25 | addItemDecoration(it) 26 | } 27 | adapter = this 28 | } 29 | } 30 | 31 | /** 32 | * Simple way to create [RecyclerView.Adapter] with view types. 33 | * @param block hare adapter can be configured 34 | * @receiver any instance of [RecyclerView] 35 | * @return a child instance of a [RecyclerView.Adapter] 36 | */ 37 | fun RecyclerView.setUp(block: TypedKidAdapterConfiguration.() -> Unit): TypedKidAdapter { 38 | val adapterDsl = TypedKidAdapterConfiguration().apply(block) 39 | return TypedKidAdapter.create(block).apply { 40 | if (layoutManager == null) { 41 | layoutManager = adapterDsl.layoutManager ?: LinearLayoutManager(context) 42 | } 43 | adapterDsl.decorator?.let { 44 | addItemDecoration(it) 45 | } 46 | adapter = this 47 | } 48 | } 49 | 50 | /** 51 | * Simple way to create [RecyclerView.Adapter] with no view types 52 | * @param block hare adapter can be configured 53 | * @param T adapter item models type. 54 | * @receiver any instance of [ViewPager2] 55 | * @return a child instance of a [RecyclerView.Adapter] 56 | */ 57 | fun ViewPager2.setUp(block: SingleKidAdapterConfiguration.() -> Unit): SingleKidAdapter { 58 | val configuration = SingleKidAdapterConfiguration().apply(block) 59 | return SingleKidAdapter(configuration).apply { 60 | adapter = this 61 | } 62 | } -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/base/BaseAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.base 2 | 3 | import androidx.recyclerview.widget.RecyclerView 4 | /* ktlint-disable no-wildcard-imports */ 5 | import java.util.* 6 | 7 | /* ktlint-enable no-wildcard-imports */ 8 | 9 | abstract class BaseAdapter>(protected var itemList: KidList) : RecyclerView.Adapter() { 10 | constructor(itemList: MutableList) : this(KidList(itemList)) 11 | 12 | override fun getItemCount() = itemList.size 13 | 14 | final override fun onBindViewHolder(holder: H, position: Int) { 15 | holder.bindView(itemList[position]) 16 | } 17 | 18 | /** 19 | * Reset all items from adapter 20 | * @param itemList new adapter items 21 | */ 22 | open operator fun plusAssign(itemList: MutableList) { 23 | this.itemList.reset(itemList) 24 | } 25 | 26 | /** 27 | * Add new items to already existing adapter items 28 | * @param itemList new adapter items 29 | */ 30 | open operator fun plus(itemList: List): BaseAdapter { 31 | this.itemList.addAll(itemList) 32 | notifyItemRangeInserted(this.itemList.lastIndex, itemList.size) 33 | return this 34 | } 35 | 36 | /** 37 | * Add new item to already existing adapter items 38 | * @param item new adapter item 39 | */ 40 | open operator fun plus(item: T): BaseAdapter { 41 | itemList.add(item) 42 | notifyItemInserted(itemList.lastIndex) 43 | return this 44 | } 45 | 46 | /** 47 | * Add new item to already existing adapter items 48 | * @param index index where to insert the item 49 | * @param item new adapter item 50 | */ 51 | open fun add(index: Int, item: T): BaseAdapter { 52 | itemList.add(index, item) 53 | notifyItemInserted(index) 54 | return this 55 | } 56 | 57 | /** 58 | * Add new item to already existing adapter items 59 | * @param items new adapter items 60 | */ 61 | open fun addAll(items: MutableList): BaseAdapter { 62 | val startPosition = itemList.size 63 | itemList.addAll(items) 64 | notifyItemRangeInserted(startPosition, items.size) 65 | return this 66 | } 67 | 68 | /** 69 | * Add new item to already existing adapter items 70 | * @param index index where to insert the item 71 | * @param items new adapter items 72 | */ 73 | open fun addAll(index: Int, items: MutableList): BaseAdapter { 74 | itemList.addAll(index, items) 75 | notifyItemRangeInserted(index, items.size) 76 | return this 77 | } 78 | 79 | /** 80 | * Replace only one item on a specific index. 81 | * @param index index of item form adapter items 82 | * @param item new adapter item 83 | */ 84 | open operator fun set(index: Int, item: T) { 85 | itemList.set(index, item) 86 | notifyItemInserted(index) 87 | } 88 | 89 | /** 90 | * Insert new items from a specific index 91 | * @param index index of item form adapter items 92 | * @param itemList new adapter items 93 | */ 94 | open fun insert(index: Int, itemList: List): BaseAdapter { 95 | this.itemList.addAll(index, itemList) 96 | notifyItemRangeChanged(index, itemList.size) 97 | return this 98 | } 99 | 100 | /** 101 | * Get a item form adapter items 102 | * @param index index of item form adapter items 103 | * @return item from adapter list by specified index 104 | */ 105 | operator fun get(index: Int): T { 106 | return itemList[index] 107 | } 108 | 109 | /** 110 | * Remove a item from adapter items 111 | * @param index index of item form adapter items 112 | */ 113 | open fun remove(index: Int): BaseAdapter { 114 | itemList.removeAt(index) 115 | notifyItemRemoved(index) 116 | return this 117 | } 118 | 119 | /** 120 | * Remove a item from adapter items 121 | * @param item item which must been removed 122 | */ 123 | open operator fun minus(item: T): BaseAdapter { 124 | val indexOfRemovedItem = itemList.indexOf(item) 125 | itemList.remove(item) 126 | notifyItemRemoved(indexOfRemovedItem) 127 | return this 128 | } 129 | 130 | /** 131 | * Remove all items from adapter 132 | */ 133 | open fun clear(): BaseAdapter { 134 | itemList.clear() 135 | notifyDataSetChanged() 136 | return this 137 | } 138 | 139 | /** 140 | * Swaps 2 items between them 141 | * @param firstIndex first index to swap 142 | * @param secondIndex second index to swap 143 | */ 144 | open fun swap(firstIndex: Int, secondIndex: Int): BaseAdapter { 145 | Collections.swap(itemList, firstIndex, secondIndex) 146 | notifyItemChanged(firstIndex) 147 | notifyItemChanged(secondIndex) 148 | return this 149 | } 150 | 151 | /** 152 | * Get copy of items in a non mutable list 153 | * Changes on result list will not affect the items from adater. 154 | */ 155 | fun getAllItems(): List = itemList.toList() 156 | } -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/base/BaseViewHolder.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.base 2 | 3 | import android.view.View 4 | import androidx.recyclerview.widget.RecyclerView 5 | 6 | abstract class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { 7 | abstract fun bindView(item: T) 8 | } -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/base/KidDiffUtilCallback.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.base 2 | 3 | import androidx.recyclerview.widget.DiffUtil 4 | 5 | internal class KidDiffUtilCallback( 6 | private val oldItems: MutableList, 7 | private val newItems: MutableList, 8 | internal var contentComparator: ((T, T) -> Boolean)? = null, 9 | internal var itemsComparator: ((T, T) -> Boolean)? = null 10 | ) : DiffUtil.Callback() { 11 | 12 | override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { 13 | return itemsComparator?.invoke(oldItems[oldItemPosition], newItems[newItemPosition]) 14 | ?: oldItems[oldItemPosition] == newItems[newItemPosition] 15 | } 16 | 17 | override fun getOldListSize(): Int = oldItems.size 18 | 19 | override fun getNewListSize(): Int = newItems.size 20 | 21 | override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { 22 | return contentComparator?.invoke(oldItems[oldItemPosition], newItems[newItemPosition]) 23 | ?: (oldItems[oldItemPosition] == newItems[newItemPosition]) 24 | } 25 | } -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/base/KidList.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.base 2 | 3 | /* ktlint-disable no-wildcard-imports */ 4 | import java.util.* 5 | /* ktlint-enable no-wildcard-imports */ 6 | 7 | open class KidList(internal var newList: MutableList = mutableListOf()) : List { 8 | private var oldList: MutableList? = null 9 | 10 | override val size: Int 11 | get() = newList.size 12 | 13 | override fun contains(element: E): Boolean = newList.contains(element) 14 | override fun containsAll(elements: Collection): Boolean = newList.containsAll(elements) 15 | 16 | override operator fun get(index: Int): E = newList[index] 17 | 18 | override fun indexOf(element: E): Int = newList.indexOf(element) 19 | 20 | override fun isEmpty(): Boolean = newList.isEmpty() 21 | 22 | override fun iterator(): MutableIterator = newList.iterator() 23 | 24 | override fun lastIndexOf(element: E): Int = newList.lastIndexOf(element) 25 | 26 | override fun listIterator(): MutableListIterator = newList.listIterator() 27 | 28 | override fun listIterator(index: Int): MutableListIterator = newList.listIterator(index) 29 | 30 | override fun subList(fromIndex: Int, toIndex: Int): MutableList { 31 | return newList.subList(fromIndex, toIndex) 32 | } 33 | 34 | private fun cacheOldItems() { 35 | oldList = newList.toMutableList() 36 | } 37 | 38 | private fun getDiffUtils() = KidDiffUtilCallback(oldList as ArrayList, newList) 39 | 40 | internal fun recycle() { 41 | oldList = null 42 | } 43 | 44 | internal fun reset(elements: MutableList): KidDiffUtilCallback { 45 | cacheOldItems() 46 | newList = elements 47 | return getDiffUtils() 48 | } 49 | 50 | internal fun add(element: E): KidDiffUtilCallback { 51 | cacheOldItems() 52 | newList.add(element) 53 | return getDiffUtils() 54 | } 55 | 56 | internal fun add(index: Int, element: E): KidDiffUtilCallback { 57 | cacheOldItems() 58 | newList.add(index, element) 59 | return getDiffUtils() 60 | } 61 | 62 | internal fun addAll(index: Int, elements: Collection): KidDiffUtilCallback { 63 | cacheOldItems() 64 | newList.addAll(index, elements) 65 | return getDiffUtils() 66 | } 67 | 68 | internal fun addAll(elements: Collection): KidDiffUtilCallback { 69 | cacheOldItems() 70 | newList.addAll(elements) 71 | return getDiffUtils() 72 | } 73 | 74 | internal fun clear(): KidDiffUtilCallback { 75 | cacheOldItems() 76 | newList.clear() 77 | return getDiffUtils() 78 | } 79 | 80 | internal fun remove(element: E): KidDiffUtilCallback { 81 | cacheOldItems() 82 | newList.remove(element) 83 | return getDiffUtils() 84 | } 85 | 86 | internal fun removeAll(elements: Collection): KidDiffUtilCallback { 87 | cacheOldItems() 88 | newList.removeAll(elements) 89 | return getDiffUtils() 90 | } 91 | 92 | internal fun removeAt(index: Int): KidDiffUtilCallback { 93 | cacheOldItems() 94 | newList.removeAt(index) 95 | return getDiffUtils() 96 | } 97 | 98 | internal fun retainAll(elements: Collection): KidDiffUtilCallback { 99 | cacheOldItems() 100 | newList.retainAll(elements) 101 | return getDiffUtils() 102 | } 103 | 104 | internal fun set(index: Int, element: E): KidDiffUtilCallback { 105 | cacheOldItems() 106 | newList[index] = element 107 | return getDiffUtils() 108 | } 109 | 110 | internal fun swap(firstIndex: Int, secondIndex: Int): KidDiffUtilCallback { 111 | cacheOldItems() 112 | Collections.swap(newList, firstIndex, secondIndex) 113 | return getDiffUtils() 114 | } 115 | 116 | internal fun update(block: (MutableList) -> Unit): KidDiffUtilCallback { 117 | cacheOldItems() 118 | block(newList) 119 | return getDiffUtils() 120 | } 121 | } -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/exceptions/KidExceptions.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.exceptions 2 | 3 | /** 4 | * Common exception 5 | */ 6 | open class KidException(message: String, cause: Throwable? = null) : Throwable(message, cause) 7 | 8 | /** 9 | * Is thrown when adapter layout resource id is not defined. 10 | */ 11 | open class UndefinedLayout(message: String) : KidException(message) 12 | 13 | /** 14 | * Is thrown when you try to update a undeclared view type. For example when you try to insert a string in a int list. 15 | */ 16 | open class UndeclaredTypeModification(modelType: Class<*>?) : KidException( 17 | "Sorry but $modelType isn't declared as a view type. " + 18 | "You try to update non-existent view type, you can update only declared view types, " + 19 | "please declare view type with withViewType() on adapter creation time method before update it" 20 | ) 21 | 22 | /** 23 | * Is thrown when you try to update a item with by undeclared tag. 24 | */ 25 | open class UndeclaredTag(tag: String) : KidException( 26 | "There are no view types with tag = $tag. Tag should be explicitly " + 27 | "declared with dsl method \"withViewType(TAG, configuration)\"" 28 | ) 29 | 30 | /** 31 | * Is thrown when you try to update items with different items type. 32 | */ 33 | open class WrongTagType(tag: String) : KidException( 34 | "Sorry but $tag is set with different items type or another with " + 35 | "view type." 36 | ) -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/simple/SingleKidAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.simple 2 | 3 | import android.view.LayoutInflater 4 | import android.view.View 5 | import android.view.ViewGroup 6 | import androidx.recyclerview.widget.DiffUtil 7 | import androidx.recyclerview.widget.RecyclerView 8 | import com.link184.kidadapter.base.BaseAdapter 9 | import com.link184.kidadapter.base.BaseViewHolder 10 | import com.link184.kidadapter.base.KidDiffUtilCallback 11 | 12 | open class SingleKidAdapter(private val configuration: SingleKidAdapterConfiguration) : 13 | BaseAdapter>(configuration.items) { 14 | init { 15 | configuration.validate() 16 | } 17 | 18 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder { 19 | val view = configuration.viewInitializer?.invoke(parent.context) 20 | ?: LayoutInflater.from(parent.context).inflate(configuration.layoutResId, parent, false) 21 | val viewHolder = object : BaseViewHolder(view) { 22 | override fun bindView(item: T) { 23 | configuration.bindHolderIndexed(itemView, item, adapterPosition) 24 | configuration.bindHolder(itemView, item) 25 | } 26 | } 27 | val itemView = viewHolder.itemView 28 | itemView.setOnClickListener { 29 | val adapterPosition = viewHolder.adapterPosition 30 | if (adapterPosition != RecyclerView.NO_POSITION) { 31 | onItemClick(itemView, adapterPosition) 32 | } 33 | } 34 | return viewHolder 35 | } 36 | 37 | open fun onItemClick(itemView: View, position: Int) {} 38 | 39 | override operator fun plusAssign(itemList: MutableList) { 40 | if (itemList != this.itemList) { 41 | this.itemList.reset(itemList).also(::dispatchUpdates) 42 | } 43 | } 44 | 45 | override operator fun plus(itemList: List): BaseAdapter> { 46 | this.itemList.addAll(itemList).also(::dispatchUpdates) 47 | return this 48 | } 49 | 50 | override operator fun plus(item: T): BaseAdapter> { 51 | itemList.add(item).also(::dispatchUpdates) 52 | return this 53 | } 54 | 55 | override fun add(index: Int, item: T): BaseAdapter> { 56 | itemList.add(index, item).also(::dispatchUpdates) 57 | return this 58 | } 59 | 60 | override fun addAll(items: MutableList): BaseAdapter> { 61 | itemList.addAll(items).also(::dispatchUpdates) 62 | return this 63 | } 64 | 65 | override fun addAll(index: Int, items: MutableList): BaseAdapter> { 66 | itemList.addAll(index, items).also(::dispatchUpdates) 67 | return this 68 | } 69 | 70 | override operator fun set(index: Int, item: T) { 71 | itemList.set(index, item).also(::dispatchUpdates) 72 | } 73 | 74 | override fun insert(index: Int, itemList: List): BaseAdapter> { 75 | this.itemList.addAll(index, itemList).also(::dispatchUpdates) 76 | return this 77 | } 78 | 79 | override fun remove(index: Int): BaseAdapter> { 80 | itemList.removeAt(index).also(::dispatchUpdates) 81 | return this 82 | } 83 | 84 | override operator fun minus(item: T): BaseAdapter> { 85 | itemList.remove(item).also(::dispatchUpdates) 86 | return this 87 | } 88 | 89 | override fun clear(): BaseAdapter> { 90 | itemList.clear().also(::dispatchUpdates) 91 | return this 92 | } 93 | 94 | infix fun update(block: (MutableList) -> Unit): BaseAdapter> { 95 | itemList.update(block).also(::dispatchUpdates) 96 | return this 97 | } 98 | 99 | private fun dispatchUpdates(diffUtilCallback: KidDiffUtilCallback) { 100 | with(diffUtilCallback) { 101 | contentComparator = configuration.contentComparator 102 | itemsComparator = configuration.itemsComparator 103 | DiffUtil.calculateDiff(this).dispatchUpdatesTo(this@SingleKidAdapter) 104 | } 105 | } 106 | 107 | companion object Factory { 108 | 109 | /** 110 | * Just create an instance of [SingleKidAdapter] without to attach it [RecyclerView] 111 | * @param block hare adapter can be configured 112 | * @return a child instance of a [RecyclerView.Adapter] 113 | */ 114 | fun create(block: SingleKidAdapterConfiguration.() -> Unit): SingleKidAdapter { 115 | val configuration = SingleKidAdapterConfiguration().apply(block) 116 | return SingleKidAdapter(configuration) 117 | } 118 | } 119 | } -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/simple/SingleKidAdapterConfiguration.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.simple 2 | 3 | import android.content.Context 4 | import android.view.View 5 | import androidx.annotation.LayoutRes 6 | import androidx.recyclerview.widget.RecyclerView 7 | import com.link184.kidadapter.BindDsl 8 | import com.link184.kidadapter.ConfigurationDsl 9 | import com.link184.kidadapter.base.KidList 10 | import com.link184.kidadapter.exceptions.UndefinedLayout 11 | 12 | class SingleKidAdapterConfiguration { 13 | internal var items = KidList() 14 | private set 15 | internal var layoutManager: RecyclerView.LayoutManager? = null 16 | private set 17 | internal var decorator: RecyclerView.ItemDecoration? = null 18 | private set 19 | @LayoutRes 20 | internal var layoutResId: Int = -1 21 | private set 22 | internal var viewInitializer: (Context.() -> View)? = null 23 | private set 24 | internal var bindHolderIndexed: View.(T, Int) -> Unit = { item, i -> } 25 | private set 26 | internal var bindHolder: View.(T) -> Unit = { } 27 | private set 28 | internal var contentComparator: ((T, T) -> Boolean)? = null 29 | internal var itemsComparator: ((T, T) -> Boolean)? = null 30 | 31 | /** 32 | * Set adapter view type items here. 33 | * @param items items to be inserted in RecyclerView. 34 | */ 35 | @ConfigurationDsl 36 | fun withItems(items: MutableList) { 37 | this.items.reset(items) 38 | } 39 | 40 | /** 41 | * Set adapter view type item here. 42 | * @param item item to be inserted in RecyclerView 43 | */ 44 | @ConfigurationDsl 45 | fun withItem(item: T) { 46 | this.items.reset(mutableListOf(item)) 47 | } 48 | 49 | /** 50 | * Set [androidx.recyclerview.widget.RecyclerView.LayoutManager] of a current [RecyclerView]. 51 | * By default it is a vertical [androidx.recyclerview.widget.LinearLayoutManager] 52 | */ 53 | @ConfigurationDsl 54 | fun withLayoutManager(layoutManager: RecyclerView.LayoutManager) { 55 | this.layoutManager = layoutManager 56 | } 57 | 58 | /** 59 | * Set [RecyclerView.ItemDecoration] of a current [RecyclerView] 60 | */ 61 | @ConfigurationDsl 62 | fun withItemDecorator(decorator: RecyclerView.ItemDecoration) { 63 | this.decorator = decorator 64 | } 65 | 66 | /** 67 | * Set [RecyclerView.ItemDecoration] of a current [RecyclerView] 68 | * @param block configure your decorator here. 69 | */ 70 | @ConfigurationDsl 71 | fun withItemDecorator(block: () -> RecyclerView.ItemDecoration) { 72 | this.decorator = block() 73 | } 74 | 75 | /** 76 | * Set [RecyclerView.LayoutManager] of a current [RecyclerView]. 77 | * By default it is a vertical [LinearLayoutManager] 78 | * @param block configure your layout manager here 79 | */ 80 | @ConfigurationDsl 81 | fun withLayoutManager(block: () -> RecyclerView.LayoutManager?) { 82 | layoutManager = block() 83 | } 84 | 85 | /** 86 | * Set layout resource id which will be bounded to actual view type 87 | * @param layoutResId desired layout resource id 88 | */ 89 | @ConfigurationDsl 90 | fun withLayoutResId(@LayoutRes layoutResId: Int) { 91 | this.layoutResId = layoutResId 92 | } 93 | 94 | /** 95 | * Set view which will be bounded to actual view type 96 | * @param viewInitializer view initialization lambda function. 97 | * Initialize your view with [Context] from this lambda. 98 | */ 99 | @ConfigurationDsl 100 | fun withLayoutView(viewInitializer: Context.() -> View) { 101 | this.viewInitializer = viewInitializer 102 | } 103 | 104 | /** 105 | * Equivalent to [DiffUtil.Callback.areContentsTheSame]. Method call is optional, by default in compare objects 106 | * by equals, if you want another behavior then please implement it here. 107 | */ 108 | @ConfigurationDsl 109 | fun withContentComparator(contentComparator: (T, T) -> Boolean) { 110 | this.contentComparator = contentComparator 111 | } 112 | 113 | /** 114 | * Equivalent to [DiffUtil.Callback.areItemsTheSame]. Method call is optional, by default in compare objects 115 | * by equals, if you want another behavior then please implement it here. 116 | */ 117 | @ConfigurationDsl 118 | fun withItemsComparator(itemsComparator: (T, T) -> Boolean) { 119 | this.itemsComparator = itemsComparator 120 | } 121 | 122 | /** 123 | * Set action which must been called when [ecyclerView.Adapter.onBindViewHolder] 124 | * @param block is executed in [RecyclerView.ViewHolder.itemView] context 125 | * @param block.item item from adapter list at adapter position, equivalent of itemsList.get(adapterPosition] 126 | * @param block.index adapterPosition 127 | */ 128 | @BindDsl 129 | fun bindIndexed(block: View.(item: T, index: Int) -> Unit) { 130 | this.bindHolderIndexed = block 131 | } 132 | 133 | /** 134 | * Set action which must been called when [ecyclerView.Adapter.onBindViewHolder] 135 | * @param block is executed in [RecyclerView.ViewHolder.itemView] context 136 | * @param block.item item from adapter list at adapter position, equivalent of itemsList.get(adapterPosition] 137 | */ 138 | @BindDsl 139 | fun bind(block: View.(T) -> Unit) { 140 | this.bindHolder = block 141 | } 142 | 143 | internal fun validate() { 144 | when { 145 | layoutResId == -1 && viewInitializer == null && items.isNotEmpty() -> throw UndefinedLayout( 146 | "Adapter layout is not set, " + 147 | "please declare it with withLayoutResId() or withLayoutView() function" 148 | ) 149 | viewInitializer != null && layoutResId != -1 -> throw UndefinedLayout( 150 | "The layout is defined through both functions (withLayoutResId and withLayoutView)" + 151 | "can`t decide which layout to pick" 152 | ) 153 | } 154 | } 155 | } -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/typed/AdapterViewType.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.typed 2 | 3 | class AdapterViewType(fromPosition: Int, block: AdapterViewTypeConfiguration.() -> Unit) { 4 | internal val configuration = AdapterViewTypeConfiguration().apply(block) 5 | internal var positionRange: IntRange = fromPosition until (fromPosition + configuration.getInternalItems().size) 6 | internal var tag: String? = null 7 | val viewType: Int = this.hashCode() 8 | 9 | internal constructor(tag: String? = null, fromPosition: Int, block: AdapterViewTypeConfiguration.() -> Unit): this(fromPosition, block) { 10 | this.tag = tag 11 | } 12 | } -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/typed/AdapterViewTypeConfiguration.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.typed 2 | 3 | import android.content.Context 4 | import android.view.View 5 | import androidx.annotation.LayoutRes 6 | import com.link184.kidadapter.BindDsl 7 | import com.link184.kidadapter.ConfigurationDsl 8 | import com.link184.kidadapter.base.KidDiffUtilCallback 9 | import com.link184.kidadapter.base.KidList 10 | import com.link184.kidadapter.exceptions.UndefinedLayout 11 | 12 | class AdapterViewTypeConfiguration { 13 | private var internalItems: KidList = KidList() 14 | @LayoutRes 15 | var layoutResId: Int = -1 16 | private set 17 | var viewInitializer: (Context.() -> View)? = null 18 | private set 19 | internal var bindHolderIndexed: View.(Any, Int) -> Unit = { _, _ -> } 20 | internal var bindHolder: View.(Any) -> Unit = { } 21 | private set 22 | var modelType: Class<*>? = null 23 | private var contentComparator: ((Any, Any) -> Boolean)? = null 24 | private var itemsComparator: ((Any, Any) -> Boolean)? = null 25 | internal var diffCallback: KidDiffUtilCallback? = null 26 | get() = field?.apply { 27 | this.contentComparator = this@AdapterViewTypeConfiguration.contentComparator 28 | this.itemsComparator = this@AdapterViewTypeConfiguration.itemsComparator 29 | } 30 | 31 | /** 32 | * Set adapter view type items here. 33 | * @param items items to be inserted in RecyclerView. 34 | */ 35 | @ConfigurationDsl 36 | inline fun withItems(items: MutableList) { 37 | setInternalItems(items as MutableList) 38 | this.modelType = T::class.java 39 | } 40 | 41 | /** 42 | * Set adapter view type item here. 43 | * @param item item to be inserted in RecyclerView 44 | */ 45 | @ConfigurationDsl 46 | inline fun withItem(item: T) { 47 | setInternalItems(mutableListOf(item as Any)) 48 | this.modelType = T::class.java 49 | } 50 | 51 | /** 52 | * Set adapter view type initialization with empty list. Is mandatory to call because KidAdapter must know all 53 | * data types for future items update (in runtime) 54 | */ 55 | @ConfigurationDsl 56 | inline fun withEmptyList() { 57 | setInternalItems(mutableListOf()) 58 | this.modelType = T::class.java 59 | } 60 | 61 | /** 62 | * Equivalent to [DiffUtil.Callback.areContentsTheSame]. Method call is optional, by default in compare objects 63 | * by equals, if you want another behavior then please implement it here. 64 | */ 65 | @ConfigurationDsl 66 | fun withContentComparator(contentComparator: (T, T) -> Boolean) { 67 | this.contentComparator = contentComparator as (Any, Any) -> Boolean 68 | } 69 | 70 | /** 71 | * Equivalent to [DiffUtil.Callback.areItemsTheSame]. Method call is optional, by default in compare objects 72 | * by equals, if you want another behavior then please implement it here. 73 | */ 74 | @ConfigurationDsl 75 | fun withItemsComparator(itemsComparator: (T, T) -> Boolean) { 76 | this.itemsComparator = itemsComparator as (Any, Any) -> Boolean 77 | } 78 | 79 | /** 80 | * Set layout resource id which will be bounded to actual view type 81 | * @param layoutResId desired layout resource id 82 | */ 83 | @ConfigurationDsl 84 | fun withLayoutResId(@LayoutRes layoutResId: Int) { 85 | this.layoutResId = layoutResId 86 | } 87 | 88 | /** 89 | * Set view which will be bounded to actual view type 90 | * @param viewInitializer view initialization lambda function. 91 | * Initialize your view with [Context] from this lambda. 92 | */ 93 | @ConfigurationDsl 94 | fun withLayoutView(viewInitializer: Context.() -> View) { 95 | this.viewInitializer = viewInitializer 96 | } 97 | 98 | /** 99 | * Set action which must been called when [ecyclerView.Adapter.onBindViewHolder] 100 | * @param block is executed in [RecyclerView.ViewHolder.itemView] context 101 | * @param block.item item from adapter list at adapter position, equivalent of itemsList.get(adapterPosition] 102 | * @param block.index adapterPosition 103 | */ 104 | @BindDsl 105 | fun bindIndexed(block: View.(T, Int) -> Unit) { 106 | bindHolderIndexed = (block as View.(Any, Int) -> Unit) 107 | } 108 | /** 109 | * Set action which must been called when [ecyclerView.Adapter.onBindViewHolder] 110 | * @param block is executed in [RecyclerView.ViewHolder.itemView] context 111 | * @param block.item item from adapter list at adapter position, equivalent of itemsList.get(adapterPosition] 112 | */ 113 | @BindDsl 114 | fun bind(block: View.(T) -> Unit) { 115 | bindHolder = (block as View.(Any) -> Unit) 116 | } 117 | 118 | /** INGORE IT */ 119 | fun setInternalItems(items: MutableList) { 120 | diffCallback = this.internalItems.reset(items) 121 | } 122 | 123 | internal fun addAllToInternalItems(index: Int, items: MutableList) { 124 | diffCallback = internalItems.addAll(index, items) 125 | } 126 | 127 | internal fun removeAllInternalItems(items: MutableList) { 128 | diffCallback = internalItems.removeAll(items) 129 | } 130 | 131 | internal fun clearInternalItems() { 132 | internalItems.clear() 133 | } 134 | 135 | internal fun swapInternalItems(firstIndex: Int, secondIndex: Int) { 136 | diffCallback = internalItems.swap(firstIndex, secondIndex) 137 | } 138 | 139 | internal fun getInternalItems() = internalItems 140 | 141 | internal fun validate() { 142 | when { 143 | layoutResId == -1 && viewInitializer == null && internalItems.isNotEmpty() -> throw UndefinedLayout( 144 | "Adapter layout is not set, " + 145 | "please declare it with withLayoutResId() or withLayoutView() function" 146 | ) 147 | viewInitializer != null && layoutResId != -1 -> throw UndefinedLayout( 148 | "The layout is defined through both functions (withLayoutResId and withLayoutView)" + 149 | "can`t decide which layout to pick" 150 | ) 151 | } 152 | } 153 | } -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/typed/TypedKidAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.typed 2 | 3 | import android.view.LayoutInflater 4 | import android.view.View 5 | import android.view.ViewGroup 6 | import androidx.recyclerview.widget.DiffUtil 7 | import androidx.recyclerview.widget.RecyclerView 8 | import com.link184.kidadapter.ExtensionDsl 9 | import com.link184.kidadapter.base.BaseAdapter 10 | import com.link184.kidadapter.base.BaseViewHolder 11 | import com.link184.kidadapter.typed.restructure.RestructureConfiguration 12 | import com.link184.kidadapter.typed.update.UpdateConfiguration 13 | 14 | open class TypedKidAdapter( 15 | private val typedKidAdapterConfiguration: TypedKidAdapterConfiguration 16 | ) : BaseAdapter>(typedKidAdapterConfiguration.getAllItems()) { 17 | init { 18 | typedKidAdapterConfiguration.validate() 19 | } 20 | 21 | override fun getItemViewType(position: Int): Int { 22 | return typedKidAdapterConfiguration.viewTypes.first { it.positionRange.contains(position) }.viewType 23 | } 24 | 25 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder { 26 | val adapterViewType = typedKidAdapterConfiguration.viewTypes.first { it.viewType == viewType } 27 | val view = adapterViewType.configuration.viewInitializer?.invoke(parent.context) 28 | ?: LayoutInflater.from(parent.context).inflate(adapterViewType.configuration.layoutResId, parent, false) 29 | val viewHolder = object : BaseViewHolder(view) { 30 | override fun bindView(item: Any) { 31 | adapterViewType.configuration.bindHolderIndexed(itemView, item, adapterPosition) 32 | adapterViewType.configuration.bindHolder(itemView, item) 33 | } 34 | } 35 | val itemView = viewHolder.itemView 36 | itemView.setOnClickListener { 37 | val adapterPosition = viewHolder.adapterPosition 38 | if (adapterPosition != RecyclerView.NO_POSITION) { 39 | onItemClick(itemView, adapterPosition) 40 | } 41 | } 42 | return viewHolder 43 | } 44 | 45 | open fun onItemClick(itemView: View, position: Int) {} 46 | 47 | /** 48 | * Update adapter 49 | * @param block setup update logic here 50 | */ 51 | @ExtensionDsl 52 | infix fun update(block: UpdateConfiguration.() -> Unit) { 53 | val diffCallbacks = UpdateConfiguration().apply(block).doUpdate(typedKidAdapterConfiguration) 54 | this += typedKidAdapterConfiguration.getAllItems() 55 | // todo: hack to avoid : java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 1(offset:0).state:17 56 | if (itemList.size > 0) { 57 | diffCallbacks 58 | .filterNotNull() 59 | .forEach { 60 | DiffUtil.calculateDiff(it).dispatchUpdatesTo(this) 61 | } 62 | } else { 63 | notifyDataSetChanged() 64 | } 65 | itemList.recycle() 66 | } 67 | 68 | /** 69 | * Restructure view types list. 70 | * @param block restructuring logic here. View types are treated here like a simple list which can suffer 71 | * consecutively changes of his items. 72 | */ 73 | @ExtensionDsl 74 | infix fun restructure(block: RestructureConfiguration.() -> Unit) { 75 | RestructureConfiguration().apply(block).doUpdate(typedKidAdapterConfiguration) 76 | this += typedKidAdapterConfiguration.getAllItems() 77 | notifyDataSetChanged() 78 | } 79 | 80 | fun getItemsByType(tag: String? = null): MutableList { 81 | if (tag != null) { 82 | return (typedKidAdapterConfiguration.getViewTypeByTag(tag).configuration.getInternalItems() as List).toMutableList() 83 | } 84 | return (typedKidAdapterConfiguration.getItemsByType() as List).toMutableList() 85 | } 86 | 87 | companion object Factory { 88 | /** 89 | * Just create an instance of [TypedKidAdapter] without to attach it [RecyclerView] 90 | * @param block hare adapter can be configured 91 | * @return a child instance of a [RecyclerView.Adapter] 92 | */ 93 | fun create(block: TypedKidAdapterConfiguration.() -> Unit): TypedKidAdapter { 94 | val adapterDsl = TypedKidAdapterConfiguration().apply(block) 95 | return TypedKidAdapter(adapterDsl) 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/typed/TypedKidAdapterConfiguration.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.typed 2 | 3 | import androidx.recyclerview.widget.RecyclerView 4 | import com.link184.kidadapter.ConfigurationDsl 5 | import com.link184.kidadapter.exceptions.UndeclaredTag 6 | import com.link184.kidadapter.simple.SingleKidAdapterConfiguration 7 | 8 | /** 9 | * Typed Adapter configuration holder. 10 | */ 11 | class TypedKidAdapterConfiguration { 12 | internal val viewTypes = mutableListOf>() 13 | internal var layoutManager: RecyclerView.LayoutManager? = null 14 | internal var decorator: RecyclerView.ItemDecoration? = null 15 | 16 | /** 17 | * Declare adapter view type. 18 | * @param tag each view type can be associated with unique string value. Useful when you adapter contains multiple 19 | * view types with the same data type, in this case you can easily update desired view type by tag. 20 | * @param block configure your view type here. 21 | */ 22 | @ConfigurationDsl 23 | fun withViewType(tag: String? = null, block: AdapterViewTypeConfiguration.() -> Unit) { 24 | val fromPosition = 25 | viewTypes.fold(0) { acc, adapterViewType -> acc + adapterViewType.configuration.getInternalItems().size } 26 | viewTypes.add(AdapterViewType(tag, fromPosition, block)) 27 | } 28 | 29 | /** 30 | * Set [androidx.recyclerview.widget.RecyclerView.LayoutManager] of a current [RecyclerView]. 31 | * By default it is a vertical [androidx.recyclerview.widget.LinearLayoutManager] 32 | */ 33 | @ConfigurationDsl 34 | fun withLayoutManager(layoutManager: RecyclerView.LayoutManager) { 35 | this.layoutManager = layoutManager 36 | } 37 | 38 | /** 39 | * Set [RecyclerView.LayoutManager] of a current [RecyclerView]. 40 | * By default it is a vertical [LinearLayoutManager] 41 | * @param block configure your layout manager here 42 | */ 43 | @ConfigurationDsl 44 | fun withLayoutManager(block: () -> RecyclerView.LayoutManager?) { 45 | layoutManager = block() 46 | } 47 | 48 | /** 49 | * Set [RecyclerView.ItemDecoration] of a current [RecyclerView] 50 | */ 51 | @ConfigurationDsl 52 | fun withItemDecorator(decorator: RecyclerView.ItemDecoration) { 53 | this.decorator = decorator 54 | } 55 | 56 | /** 57 | * Set [RecyclerView.ItemDecoration] of a current [RecyclerView] 58 | * @param block configure your decorator here. 59 | */ 60 | @ConfigurationDsl 61 | fun withItemDecorator(block: () -> RecyclerView.ItemDecoration) { 62 | this.decorator = block() 63 | } 64 | 65 | /** 66 | * Useful to build [TypedKidAdapter] from [SingleKidAdapterConfiguration] 67 | * @param block configure your single adapter configuration here 68 | * @return typed adapter configuration transformed from single adapter configuration 69 | */ 70 | @ConfigurationDsl 71 | fun fromSimpleConfiguration(block: SingleKidAdapterConfiguration<*>.() -> Unit): TypedKidAdapterConfiguration { 72 | return TypedKidAdapterConfiguration().apply { 73 | val adapterConfiguration = SingleKidAdapterConfiguration().apply(block) 74 | withLayoutManager { adapterConfiguration.layoutManager } 75 | withViewType { 76 | withItems(adapterConfiguration.items.newList) 77 | bindIndexed { item, position -> 78 | adapterConfiguration.bindHolderIndexed(this, item, position) 79 | } 80 | bind { 81 | adapterConfiguration.bindHolder(this, it) 82 | } 83 | } 84 | } 85 | } 86 | 87 | internal fun getAllItems(): MutableList { 88 | return viewTypes 89 | .map { it.configuration.getInternalItems().toMutableList() } 90 | .fold(ArrayList()) { acc, items -> acc.apply { addAll(items) } } 91 | } 92 | 93 | /** 94 | * Get FIRST mutable list where item type is [T] 95 | * @param T model type from adapter 96 | * @return mutable list of [T] items 97 | */ 98 | internal inline fun getItemsByType(): MutableList { 99 | return viewTypes 100 | .map { it.configuration.getInternalItems().newList } 101 | .first { 102 | it.any { it is T } 103 | } as MutableList 104 | } 105 | 106 | /** 107 | * Get [AdapterViewType] by given tag. 108 | */ 109 | internal fun getViewTypeByTag(tag: String): AdapterViewType { 110 | viewTypes 111 | .filter { it.tag != null } 112 | .firstOrNull { it.tag == tag } 113 | ?.let { return it } 114 | throw UndeclaredTag(tag) 115 | } 116 | 117 | internal fun invalidateItems() { 118 | val newViewTypes = mutableListOf>() 119 | viewTypes.forEach { adapterViewType -> 120 | val fromPosition = 121 | newViewTypes.fold(0) { acc, adapterViewType -> acc + adapterViewType.configuration.getInternalItems().size } 122 | newViewTypes.add(adapterViewType) 123 | val toPosition = fromPosition + adapterViewType.configuration.getInternalItems().size 124 | adapterViewType.positionRange = fromPosition until if (toPosition < 1) 1 else toPosition 125 | } 126 | } 127 | 128 | internal fun validate() { 129 | viewTypes.forEach { it.configuration.validate() } 130 | } 131 | } -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/typed/restructure/RestructureConfiguration.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.typed.restructure 2 | 3 | import com.link184.kidadapter.ConfigurationDsl 4 | import com.link184.kidadapter.exceptions.UndeclaredTag 5 | import com.link184.kidadapter.typed.AdapterViewType 6 | import com.link184.kidadapter.typed.AdapterViewTypeConfiguration 7 | import com.link184.kidadapter.typed.TypedKidAdapterConfiguration 8 | /* ktlint-disable no-wildcard-imports */ 9 | import java.util.* 10 | /* ktlint-enable no-wildcard-imports */ 11 | 12 | class RestructureConfiguration { 13 | private val restructureQueue = mutableListOf() 14 | 15 | /** 16 | * Declare new [AdapterViewType] at a specific index 17 | * @param index index where new [AdapterViewType] must been inserted 18 | * @param newTag nullable tag. New [AdapterViewType] can be marked with a tag for future comfortable manipulation. 19 | * @param block configuration of a new [AdapterViewType] 20 | * 21 | * @throws IndexOutOfBoundsException in case of invalid index 22 | */ 23 | @ConfigurationDsl 24 | fun insert(index: Int, newTag: String? = null, block: AdapterViewTypeConfiguration.() -> Unit) { 25 | restructureQueue.add(RestructureItem(newTag, block, RestructureType.Insert.InsertMiddle(index))) 26 | } 27 | 28 | /** 29 | * Declare new [AdapterViewType] at top of all view types 30 | * @param newTag nullable tag. New [AdapterViewType] can be marked with a newTag for future comfortable manipulation. 31 | * @param block configuration of a new [AdapterViewType] 32 | * 33 | * @throws UndeclaredTag in case of invalid tag 34 | */ 35 | @ConfigurationDsl 36 | fun insertTop(newTag: String? = null, block: AdapterViewTypeConfiguration.() -> Unit) { 37 | restructureQueue.add(RestructureItem(newTag, block, RestructureType.Insert.InsertTop)) 38 | } 39 | 40 | /** 41 | * Declare new [AdapterViewType] at bottom of all view types 42 | * @param newTag nullable tag. New [AdapterViewType] can be marked with a tag for future comfortable manipulation. 43 | * @param block configuration of a new [AdapterViewType] 44 | * 45 | * @throws UndeclaredTag in case of invalid tag 46 | */ 47 | @ConfigurationDsl 48 | fun insertBottom(newTag: String? = null, block: AdapterViewTypeConfiguration.() -> Unit) { 49 | restructureQueue.add(RestructureItem(newTag, block, RestructureType.Insert.InsertBottom)) 50 | } 51 | 52 | /** 53 | * Remove [AdapterViewType] by tag 54 | * @param tag Tag which was associated to [AdapterViewType] when it was declared. 55 | * @throws UndeclaredTag in case of invalid tag 56 | */ 57 | @ConfigurationDsl 58 | fun remove(tag: String) { 59 | restructureQueue.add(RestructureItem(tag, { }, RestructureType.Remove(-1))) 60 | } 61 | 62 | /** 63 | * Remove [AdapterViewType] by index 64 | * @param index [AdapterViewType] position from where it must been removed 65 | * 66 | * @throws IndexOutOfBoundsException in case of invalid index 67 | */ 68 | @ConfigurationDsl 69 | fun remove(index: Int) { 70 | restructureQueue.add(RestructureItem(null, { }, RestructureType.Remove(index))) 71 | } 72 | 73 | /** 74 | * Removes all declared [AdapterViewType] 75 | */ 76 | @ConfigurationDsl 77 | fun removeAll() { 78 | restructureQueue.add(RestructureItem(null, { }, RestructureType.RemoveAll)) 79 | } 80 | 81 | /** 82 | * Replace [AdapterViewType] by tag 83 | * @param tag Tag which was associated to [AdapterViewType] when it was declared. This tag will be associated with 84 | * new [AdapterViewType] 85 | * @param block configuration of a new [AdapterViewType] 86 | * 87 | * @throws UndeclaredTag in case of invalid tag 88 | */ 89 | @ConfigurationDsl 90 | fun replace(tag: String, block: AdapterViewTypeConfiguration.() -> Unit) { 91 | restructureQueue.add(RestructureItem(tag, block, RestructureType.ReplaceByTag(tag))) 92 | } 93 | 94 | /** 95 | * Replace [AdapterViewType] by index 96 | * @param index [AdapterViewType] position where it must been replaced 97 | * @param newTag nullable tag. New [AdapterViewType] can be marked with a tag for future comfortable manipulation. 98 | * @param block configuration of a new [AdapterViewType] 99 | * 100 | * @throws IndexOutOfBoundsException in case of invalid index 101 | */ 102 | @ConfigurationDsl 103 | fun replace(index: Int, newTag: String? = null, block: AdapterViewTypeConfiguration.() -> Unit) { 104 | restructureQueue.add(RestructureItem(newTag, block, RestructureType.ReplaceByIndex(index))) 105 | } 106 | 107 | /** 108 | * 2 [AdapterViewType] are swapping between them. The same as [Collections.swap] 109 | * @param firstIndex the index of one element to be swapped. 110 | * @param secondIndex index of the other element to be swapped. 111 | * 112 | * @throws IndexOutOfBoundsException if either i or j 113 | * is out of range (i < 0 || i >= list.size() 114 | * || j < 0 || j >= list.size()). 115 | */ 116 | @ConfigurationDsl 117 | fun swap(firstIndex: Int, secondIndex: Int) { 118 | restructureQueue.add(RestructureItem(null, { }, RestructureType.Swap(firstIndex, secondIndex))) 119 | } 120 | 121 | internal fun doUpdate(typedKidAdapterConfiguration: TypedKidAdapterConfiguration) { 122 | val viewTypes = typedKidAdapterConfiguration.viewTypes 123 | restructureQueue.forEach { 124 | when (it.restructureType) { 125 | is RestructureType.Insert.InsertTop -> viewTypes.add(0, AdapterViewType(it.tag, 0, it.configuration)) 126 | is RestructureType.Insert.InsertBottom -> viewTypes.add(AdapterViewType(it.tag, 0, it.configuration)) 127 | is RestructureType.Insert -> viewTypes.add( 128 | it.restructureType.index, 129 | AdapterViewType(it.tag, 0, it.configuration) 130 | ) 131 | is RestructureType.Remove -> { 132 | if (it.tag != null) { 133 | viewTypes.remove(viewTypes.first { item -> item.tag == it.tag }) 134 | } 135 | if (it.restructureType.index != -1) { 136 | viewTypes.removeAt(it.restructureType.index) 137 | } 138 | } 139 | is RestructureType.RemoveAll -> viewTypes.clear() 140 | is RestructureType.ReplaceByIndex -> viewTypes[it.restructureType.index] = AdapterViewType(it.tag, 0, it.configuration) 141 | is RestructureType.ReplaceByTag -> { 142 | val index = viewTypes.indexOfFirst { item -> item.tag == it.tag } 143 | viewTypes[index] = AdapterViewType(it.tag, 0, it.configuration) 144 | } 145 | is RestructureType.Swap -> Collections.swap(viewTypes, it.restructureType.firstIndex, it.restructureType.secondIndex) 146 | } 147 | } 148 | typedKidAdapterConfiguration.invalidateItems() 149 | } 150 | } -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/typed/restructure/RestructureItem.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.typed.restructure 2 | 3 | import com.link184.kidadapter.typed.AdapterViewTypeConfiguration 4 | 5 | data class RestructureItem( 6 | val tag: String?, 7 | val configuration: AdapterViewTypeConfiguration.() -> Unit, 8 | val restructureType: RestructureType 9 | ) 10 | -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/typed/restructure/RestructureType.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.typed.restructure 2 | 3 | sealed class RestructureType { 4 | sealed class Insert(internal val index: Int) : RestructureType() { 5 | object InsertTop : Insert(0) 6 | class InsertMiddle(index: Int) : Insert(index) 7 | object InsertBottom : Insert(-1) 8 | } 9 | 10 | class ReplaceByIndex(internal val index: Int) : RestructureType() 11 | class ReplaceByTag(internal val tag: String) : RestructureType() 12 | 13 | class Remove(internal val index: Int) : RestructureType() 14 | object RemoveAll : RestructureType() 15 | 16 | class Swap(internal val firstIndex: Int, internal val secondIndex: Int) : RestructureType() 17 | 18 | fun resolveIndex(currentList: MutableList<*>): Int { 19 | if (this is Insert.InsertBottom) { 20 | return currentList.size 21 | } 22 | if (this is Insert) { 23 | return index 24 | } 25 | if (this is Remove) { 26 | return index 27 | } 28 | if (this is ReplaceByIndex) { 29 | return index 30 | } 31 | return -1 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/typed/update/UpdateConfiguration.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.typed.update 2 | 3 | import com.link184.kidadapter.ConfigurationDsl 4 | import com.link184.kidadapter.base.KidDiffUtilCallback 5 | import com.link184.kidadapter.exceptions.UndeclaredTypeModification 6 | import com.link184.kidadapter.exceptions.WrongTagType 7 | import com.link184.kidadapter.typed.AdapterViewType 8 | import com.link184.kidadapter.typed.TypedKidAdapterConfiguration 9 | /* ktlint-disable no-wildcard-imports */ 10 | import java.util.* 11 | /* ktlint-enable no-wildcard-imports */ 12 | 13 | class UpdateConfiguration { 14 | val updateQueue = mutableListOf>() 15 | 16 | /** 17 | * Insert items from specific index into already declared view typed list. 18 | * @param T data type of items which are stored in [AdapterViewType]. If there are declared more than one 19 | * [AdapterViewType] with the same data type, first [AdapterViewType] will be taken, otherwise use [tag] 20 | * @param index index from where items should been inserted 21 | * @param items a mutable list which should been inserted. 22 | * @param tag nullable tag. It must been declared on adapter initialization. 23 | */ 24 | @ConfigurationDsl 25 | inline fun insert(index: Int, items: List, tag: String? = null) { 26 | updateQueue.add(UpdateItem(T::class.java, tag, items, UpdateType.Insert.InsertMiddle(index))) 27 | } 28 | 29 | /** 30 | * Insert a item from specific index into already declared view typed list. 31 | * @param T data type of items which are stored in [AdapterViewType]. If there are declared more than one 32 | * [AdapterViewType] with the same data type, first [AdapterViewType] will be taken, otherwise use [tag] 33 | * @param index index from where items should been inserted 34 | * @param item a item which should been inserted. 35 | * @param tag nullable tag. It must been declared on adapter initialization. 36 | */ 37 | @ConfigurationDsl 38 | inline fun insert(index: Int, item: T, tag: String? = null) { 39 | updateQueue.add(UpdateItem(T::class.java, tag, item, UpdateType.Insert.InsertMiddle(index))) 40 | } 41 | 42 | /** 43 | * Insert a item from index 0 into already declared view typed list. 44 | * @param T data type of items which are stored in [AdapterViewType]. If there are declared more than one 45 | * [AdapterViewType] with the same data type, first [AdapterViewType] will be taken, otherwise use [tag] 46 | * @param item a item which should been inserted. 47 | * @param tag nullable tag. It must been declared on adapter initialization. 48 | */ 49 | @ConfigurationDsl 50 | inline fun insertTop(item: T, tag: String? = null) { 51 | updateQueue.add(UpdateItem(T::class.java, tag, item, UpdateType.Insert.InsertTop)) 52 | } 53 | 54 | /** 55 | * Insert items from index 0 into already declared view typed list. 56 | * @param T data type of items which are stored in [AdapterViewType]. If there are declared more than one 57 | * [AdapterViewType] with the same data type, first [AdapterViewType] will be taken, otherwise use [tag] 58 | * @param items a mutable list which should been inserted. 59 | * @param tag nullable tag. It must been declared on adapter initialization. 60 | */ 61 | @ConfigurationDsl 62 | inline fun insertTop(items: List, tag: String? = null) { 63 | updateQueue.add(UpdateItem(T::class.java, tag, items, UpdateType.Insert.InsertTop)) 64 | } 65 | 66 | /** 67 | * Insert a item from last index into already declared view typed list. 68 | * @param T data type of items which are stored in [AdapterViewType]. If there are declared more than one 69 | * [AdapterViewType] with the same data type, first [AdapterViewType] will be taken, otherwise use [tag] 70 | * @param item a item which should been inserted. 71 | * @param tag nullable tag. It must been declared on adapter initialization. 72 | */ 73 | @ConfigurationDsl 74 | inline fun insertBottom(item: T, tag: String? = null) { 75 | updateQueue.add(UpdateItem(T::class.java, tag, item, UpdateType.Insert.InsertBottom)) 76 | } 77 | 78 | /** 79 | * Insert items from last index into already declared view typed list. 80 | * @param T data type of items which are stored in [AdapterViewType]. If there are declared more than one 81 | * [AdapterViewType] with the same data type, first [AdapterViewType] will be taken, otherwise use [tag] 82 | * @param items a mutable list which should been inserted. 83 | * @param tag nullable tag. It must been declared on adapter initialization. 84 | */ 85 | @ConfigurationDsl 86 | inline fun insertBottom(items: List, tag: String? = null) { 87 | updateQueue.add(UpdateItem(T::class.java, tag, items, UpdateType.Insert.InsertBottom)) 88 | } 89 | 90 | /** 91 | * Replace ALL items form already declared list. 92 | * @param T data type of items which are stored in [AdapterViewType]. If there are declared more than one 93 | * [AdapterViewType] with the same data type, first [AdapterViewType] will be taken, otherwise use [tag] 94 | * @param items a mutable list which should been replaced. 95 | * @param tag nullable tag. It must been declared on adapter initialization. 96 | */ 97 | @ConfigurationDsl 98 | inline fun replaceAllItems(items: List, tag: String? = null) { 99 | updateQueue.add(UpdateItem(T::class.java, tag, items, UpdateType.ReplaceAll)) 100 | } 101 | 102 | /** 103 | * Remove items from already declared list. 104 | * @param T data type of items which are stored in [AdapterViewType]. If there are declared more than one 105 | * [AdapterViewType] with the same data type, first [AdapterViewType] will be taken, otherwise use [tag] 106 | * @param items a mutable list which should been removed. 107 | * @param tag nullable tag. It must been declared on adapter initialization. 108 | */ 109 | @ConfigurationDsl 110 | inline fun removeItems(items: List, tag: String? = null) { 111 | updateQueue.add(UpdateItem(T::class.java, tag, items, UpdateType.Remove)) 112 | } 113 | 114 | /** 115 | * Remove all items from already declared list. 116 | * @param T data type of items which are stored in [AdapterViewType]. If there are declared more than one 117 | * [AdapterViewType] with the same data type, first [AdapterViewType] will be taken, otherwise use [tag] 118 | * @param tag nullable tag. It must been declared on adapter initialization. 119 | */ 120 | @ConfigurationDsl 121 | inline fun removeAll(tag: String? = null) { 122 | updateQueue.add(UpdateItem(T::class.java, tag, mutableListOf(), UpdateType.Remove)) 123 | } 124 | 125 | /** 126 | * 2 items from [AdapterViewType] are swapping between them. The same as [Collections.swap] 127 | * @param T data type of items which are stored in [AdapterViewType]. If there are declared more than one 128 | * [AdapterViewType] with the same data type, first [AdapterViewType] will be taken, otherwise use [tag] 129 | * @param firstIndex the index of one element to be swapped. 130 | * @param secondIndex index of the other element to be swapped. 131 | * @param tag nullable tag. It must been declared on adapter initialization. 132 | * 133 | * @throws IndexOutOfBoundsException if either i or j 134 | * is out of range (i < 0 || i >= list.size() 135 | * || j < 0 || j >= list.size()). 136 | */ 137 | @ConfigurationDsl 138 | inline fun swap(firstIndex: Int, secondIndex: Int, tag: String? = null) { 139 | updateQueue.add(UpdateItem(T::class.java, tag, mutableListOf(), UpdateType.Swap(firstIndex, secondIndex))) 140 | } 141 | 142 | internal fun doUpdate(typedKidAdapterConfiguration: TypedKidAdapterConfiguration): MutableList?> { 143 | val diffCallbacks = mutableListOf?>() 144 | updateQueue.forEach { 145 | when (it.updateType) { 146 | is UpdateType.Insert -> insert(it, typedKidAdapterConfiguration).let(diffCallbacks::add) 147 | is UpdateType.ReplaceAll -> replaceItems(it, typedKidAdapterConfiguration).let(diffCallbacks::add) 148 | is UpdateType.Remove -> removeItems(it, typedKidAdapterConfiguration).let(diffCallbacks::add) 149 | is UpdateType.Swap -> swapItems(it, typedKidAdapterConfiguration).let(diffCallbacks::add) 150 | } 151 | } 152 | typedKidAdapterConfiguration.invalidateItems() 153 | return diffCallbacks 154 | } 155 | 156 | private fun insert( 157 | item: UpdateItem<*>, 158 | typedKidAdapterConfiguration: TypedKidAdapterConfiguration 159 | ): KidDiffUtilCallback? { 160 | val viewType = getAdapterViewTypeByType(item, typedKidAdapterConfiguration) 161 | viewType.configuration.addAllToInternalItems( 162 | item.updateType.resolveIndex(viewType.configuration.getInternalItems().newList), 163 | item.items as MutableList 164 | ) 165 | return viewType.configuration.diffCallback 166 | } 167 | 168 | private fun replaceItems( 169 | item: UpdateItem<*>, 170 | typedKidAdapterConfiguration: TypedKidAdapterConfiguration 171 | ): KidDiffUtilCallback? { 172 | val viewType = getAdapterViewTypeByType(item, typedKidAdapterConfiguration) 173 | viewType.configuration.setInternalItems(item.items as MutableList) 174 | return viewType.configuration.diffCallback 175 | } 176 | 177 | private fun removeItems( 178 | item: UpdateItem<*>, 179 | typedKidAdapterConfiguration: TypedKidAdapterConfiguration 180 | ): KidDiffUtilCallback? { 181 | val viewType = getAdapterViewTypeByType(item, typedKidAdapterConfiguration) 182 | if (item.items.isNotEmpty()) { 183 | viewType.configuration.removeAllInternalItems(item.items as MutableList) 184 | } else { 185 | viewType.configuration.clearInternalItems() 186 | } 187 | return viewType.configuration.diffCallback 188 | } 189 | 190 | private fun swapItems( 191 | item: UpdateItem<*>, 192 | typedKidAdapterConfiguration: TypedKidAdapterConfiguration 193 | ): KidDiffUtilCallback? { 194 | val viewType = getAdapterViewTypeByType(item, typedKidAdapterConfiguration) 195 | val swapUpdateType = item.updateType as UpdateType.Swap 196 | viewType.configuration.swapInternalItems(swapUpdateType.firstIndex, swapUpdateType.secondIndex) 197 | return viewType.configuration.diffCallback 198 | } 199 | 200 | private fun getAdapterViewTypeByType( 201 | item: UpdateItem, 202 | typedKidAdapterConfiguration: TypedKidAdapterConfiguration 203 | ): AdapterViewType { 204 | item.tag?.let { 205 | return typedKidAdapterConfiguration.getViewTypeByTag(it).also { byTypeItem -> 206 | if (byTypeItem.configuration.modelType != item.modelType) { 207 | throw WrongTagType(it) 208 | } 209 | } 210 | } 211 | 212 | val itemIsPresent = typedKidAdapterConfiguration.viewTypes.any { it.configuration.modelType == item.modelType } 213 | if (!itemIsPresent) { 214 | throw UndeclaredTypeModification(item.modelType) 215 | } 216 | return typedKidAdapterConfiguration.viewTypes.first { it.configuration.modelType == item.modelType } 217 | } 218 | } -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/typed/update/UpdateItem.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.typed.update 2 | 3 | data class UpdateItem( 4 | val modelType: Class?, 5 | val tag: String?, 6 | val items: List, 7 | val updateType: UpdateType 8 | ) { 9 | constructor(modelType: Class, tag: String?, item: T, updateType: UpdateType) 10 | : this(modelType, tag, mutableListOf(item), updateType) 11 | } -------------------------------------------------------------------------------- /library/src/main/java/com/link184/kidadapter/typed/update/UpdateType.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter.typed.update 2 | 3 | sealed class UpdateType { 4 | sealed class Insert(internal val index: Int) : UpdateType() { 5 | object InsertTop : Insert(0) 6 | class InsertMiddle(index: Int) : Insert(index) 7 | object InsertBottom : Insert(-1) 8 | } 9 | 10 | object ReplaceAll : UpdateType() 11 | object Remove : UpdateType() 12 | 13 | class Swap(val firstIndex: Int, val secondIndex: Int) : UpdateType() 14 | 15 | fun resolveIndex(currentList: MutableList<*>): Int { 16 | if (this is Insert.InsertBottom) { 17 | return currentList.size 18 | } 19 | if (this is Insert) { 20 | return index 21 | } 22 | return -1 23 | } 24 | } -------------------------------------------------------------------------------- /library/src/test/java/com/link184/kidadapter/ErrorCasesTest.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter 2 | 3 | /* ktlint-disable no-wildcard-imports */ 4 | /* ktlint-enable no-wildcard-imports */ 5 | import android.os.Build 6 | import android.widget.TextView 7 | import com.link184.kidadapter.exceptions.UndeclaredTag 8 | import com.link184.kidadapter.exceptions.UndeclaredTypeModification 9 | import com.link184.kidadapter.exceptions.UndefinedLayout 10 | import com.link184.kidadapter.exceptions.WrongTagType 11 | import org.junit.Before 12 | import org.junit.FixMethodOrder 13 | import org.junit.Test 14 | import org.junit.runner.RunWith 15 | import org.junit.runners.MethodSorters 16 | import org.robolectric.Robolectric 17 | import org.robolectric.RobolectricTestRunner 18 | import org.robolectric.android.controller.ActivityController 19 | import org.robolectric.annotation.Config 20 | import kotlin.test.assertFailsWith 21 | 22 | @RunWith(RobolectricTestRunner::class) 23 | @Config(sdk = [Build.VERSION_CODES.UPSIDE_DOWN_CAKE]) 24 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 25 | class ErrorCasesTest { 26 | lateinit var activityController: ActivityController 27 | @Before 28 | fun setUp() { 29 | activityController = Robolectric.buildActivity(RecyclerViewActivity::class.java) 30 | } 31 | 32 | @Test 33 | fun t1_withoutLayoutResource() { 34 | assertFailsWith { 35 | activityController.get().recyclerView.setUp { 36 | withItems(mutableListOf("one", "two")) 37 | bind { 38 | } 39 | } 40 | } 41 | 42 | assertFailsWith { 43 | activityController.get().recyclerView.setUp { 44 | withViewType { 45 | withItems(mutableListOf("one", "two", "three")) 46 | bind { 47 | } 48 | } 49 | } 50 | } 51 | } 52 | 53 | @Test 54 | fun t2_withLayoutResAndViewDefined() { 55 | assertFailsWith { 56 | activityController.get().recyclerView.setUp { 57 | withItems(mutableListOf("One", "Two")) 58 | withLayoutResId(android.R.layout.list_content) 59 | withLayoutView(::TextView) 60 | bind { } 61 | } 62 | } 63 | 64 | assertFailsWith { 65 | activityController.get().recyclerView.setUp { 66 | withViewType { 67 | withItems(mutableListOf("one", "two")) 68 | withLayoutResId(android.R.layout.list_content) 69 | withLayoutView(::TextView) 70 | bind { } 71 | } 72 | } 73 | } 74 | } 75 | 76 | @Test 77 | fun t2_zeroViewTypes() { 78 | activityController.get().recyclerView.setUp { } 79 | } 80 | 81 | @Test 82 | fun t3_undeclaredTypeUpdate() { 83 | val adapter = activityController.get().recyclerView.setUp { 84 | withViewType { 85 | withItems(mutableListOf("one", "two")) 86 | withLayoutResId(android.R.layout.list_content) 87 | bind { } 88 | } 89 | } 90 | 91 | assertFailsWith { 92 | adapter update { 93 | insertTop(1_000_000_000) 94 | } 95 | } 96 | 97 | assertFailsWith { 98 | adapter update { 99 | insertBottom(333_333, "UNDEFINED TAG") 100 | } 101 | } 102 | } 103 | 104 | @Test 105 | fun t4_wrongTag() { 106 | val adapter = activityController.get().recyclerView.setUp { 107 | withViewType("first_tag") { 108 | withItems(mutableListOf("one", "two")) 109 | withLayoutResId(android.R.layout.list_content) 110 | bind { } 111 | } 112 | 113 | withViewType("second_tag") { 114 | withItems(mutableListOf(1, 2, 3)) 115 | withLayoutResId(android.R.layout.list_content) 116 | bind { } 117 | } 118 | } 119 | 120 | assertFailsWith { 121 | adapter update { 122 | insertTop(mutableListOf(4, 5, 6), "first_tag") 123 | } 124 | } 125 | } 126 | } -------------------------------------------------------------------------------- /library/src/test/java/com/link184/kidadapter/MockUtils.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter 2 | 3 | import org.mockito.Mockito 4 | import org.mockito.Mockito.RETURNS_DEEP_STUBS 5 | 6 | inline fun mock(): T = Mockito.mock(T::class.java) 7 | inline fun spy(): T = Mockito.spy(T::class.java) 8 | fun spy(obj: T): T = Mockito.spy(obj) 9 | 10 | inline fun deepMock(): T = Mockito.mock(T::class.java, RETURNS_DEEP_STUBS) 11 | 12 | fun anyNullableObject(): T { 13 | Mockito.any() 14 | return uninitialized() 15 | } 16 | 17 | @Suppress("UNCHECKED_CAST") 18 | private fun uninitialized(): T = null as T -------------------------------------------------------------------------------- /library/src/test/java/com/link184/kidadapter/MultiAdapterTest.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter 2 | 3 | import android.os.Build 4 | import com.link184.kidadapter.typed.TypedKidAdapter 5 | import com.link184.kidadapter.typed.TypedKidAdapterConfiguration 6 | import org.junit.Before 7 | import org.junit.FixMethodOrder 8 | import org.junit.Test 9 | import org.junit.runner.RunWith 10 | import org.junit.runners.MethodSorters 11 | import org.mockito.ArgumentMatchers 12 | import org.mockito.ArgumentMatchers.anyInt 13 | import org.mockito.Mockito 14 | import org.mockito.internal.verification.VerificationModeFactory 15 | import org.robolectric.Robolectric 16 | import org.robolectric.RobolectricTestRunner 17 | import org.robolectric.android.controller.ActivityController 18 | import org.robolectric.annotation.Config 19 | import kotlin.test.assertEquals 20 | import kotlin.test.assertNotNull 21 | import kotlin.test.assertTrue 22 | 23 | @RunWith(RobolectricTestRunner::class) 24 | @Config(sdk = [Build.VERSION_CODES.UPSIDE_DOWN_CAKE]) 25 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 26 | class MultiAdapterTest { 27 | private lateinit var activityController: ActivityController 28 | 29 | private val stringItems = mutableListOf("a", "b", "c", "d") 30 | private val stringBindFunction: TypedKidAdapterConfiguration.(String) -> Unit = { } 31 | private var stringBindFunctionSpy = spy(stringBindFunction) 32 | private val intItems = mutableListOf(1, 2, 3, 4, 5, 9) 33 | private val intBindFunction: TypedKidAdapterConfiguration.(Int) -> Unit = { } 34 | private var intBindFunctionSpy = spy(intBindFunction) 35 | private val anyItems = mutableListOf(Any(), Any(), Any(), Any()) 36 | private val anyBindFunction: TypedKidAdapterConfiguration.(Any) -> Unit = { } 37 | private var anyBindFunctionSpy = spy(anyBindFunction) 38 | 39 | @Before 40 | fun setUp() { 41 | activityController = Robolectric.buildActivity(RecyclerViewActivity::class.java) 42 | resetSpys() 43 | } 44 | 45 | private fun resetSpys() { 46 | stringBindFunctionSpy = spy(stringBindFunction) 47 | intBindFunctionSpy = spy(intBindFunction) 48 | anyBindFunctionSpy = spy(anyBindFunction) 49 | } 50 | 51 | private fun populateRecyclerView(): TypedKidAdapter { 52 | return activityController.get().recyclerView.setUp { 53 | withViewType { 54 | withItems(stringItems) 55 | withLayoutResId(android.R.layout.list_content) 56 | bind { 57 | assertTrue(stringItems.contains(it)) 58 | stringBindFunctionSpy(it) 59 | } 60 | } 61 | 62 | withViewType { 63 | withItems(intItems) 64 | withLayoutResId(android.R.layout.list_content) 65 | bind { 66 | assertTrue(intItems.contains(it)) 67 | intBindFunctionSpy(it) 68 | } 69 | } 70 | 71 | withViewType { 72 | withItems(anyItems) 73 | withLayoutResId(android.R.layout.list_content) 74 | bind { 75 | assertTrue(anyItems.contains(it)) 76 | anyBindFunctionSpy(it) 77 | } 78 | } 79 | } 80 | } 81 | 82 | @Test 83 | fun t1_viewTypeAdapterPopulateTest() { 84 | val adapter = populateRecyclerView() 85 | 86 | activityController.create().start().visible() 87 | Mockito.verify(stringBindFunctionSpy, VerificationModeFactory.times(stringItems.size)) 88 | .invoke(anyNullableObject(), anyNullableObject()) 89 | Mockito.verify(intBindFunctionSpy, VerificationModeFactory.times(intItems.size)).invoke( 90 | anyNullableObject(), 91 | ArgumentMatchers.anyInt() 92 | ) 93 | Mockito.verify(anyBindFunctionSpy, VerificationModeFactory.times(anyItems.size)) 94 | .invoke(anyNullableObject(), anyNullableObject()) 95 | 96 | val itemsByStringType = adapter.getItemsByType() 97 | assertEquals(stringItems, itemsByStringType) 98 | } 99 | 100 | @Test 101 | fun t2_viewTypeAdapterUpdateTest() { 102 | val adapter = populateRecyclerView() 103 | assertNotNull(adapter) 104 | 105 | val topList = mutableListOf("x", "y", "z") 106 | val bottomList = mutableListOf(11, 22, 33, 44) 107 | 108 | adapter update { 109 | insertTop(topList) 110 | insertBottom(bottomList) 111 | } 112 | 113 | activityController.create().start().visible() 114 | 115 | Mockito.verify(stringBindFunctionSpy, VerificationModeFactory.times(stringItems.size)) 116 | .invoke(anyNullableObject(), anyNullableObject()) 117 | Mockito.verify(intBindFunctionSpy, VerificationModeFactory.times(intItems.size)) 118 | .invoke(anyNullableObject(), anyInt()) 119 | 120 | resetSpys() 121 | val removeItems = mutableListOf("x", "y") 122 | adapter update { 123 | removeItems(removeItems) 124 | } 125 | 126 | activityController.stop().create().start().visible() 127 | 128 | Mockito.verify(stringBindFunctionSpy, VerificationModeFactory.times(stringItems.size)) 129 | .invoke(anyNullableObject(), anyNullableObject()) 130 | 131 | resetSpys() 132 | val insertList = mutableListOf("insert1", "insert2") 133 | val insertIndex = 2 134 | adapter update { 135 | insert(insertIndex, insertList) 136 | } 137 | 138 | activityController.stop().create().start().visible() 139 | 140 | assertTrue { stringItems[insertIndex] == insertList.first() } 141 | 142 | resetSpys() 143 | adapter update { 144 | removeAll() 145 | removeAll() 146 | removeAll() 147 | } 148 | activityController.stop().create().start().visible() 149 | 150 | assertTrue { adapter.itemCount == 0 } 151 | } 152 | 153 | @Test 154 | fun t3_viewTypeAdapterSwapTest() { 155 | val adapter = populateRecyclerView() 156 | val newList = mutableListOf(1, 2, 3, 4, 5) 157 | adapter restructure { 158 | insertBottom("shortList") { 159 | withItems(newList.toMutableList()) 160 | withLayoutResId(android.R.layout.list_content) 161 | } 162 | } 163 | adapter update { 164 | swap(0, 3) 165 | } 166 | 167 | activityController.stop().create().start().visible() 168 | 169 | assertTrue { 170 | val firstItem = adapter.getItemsByType("shortList")[0] 171 | val secondItem = adapter.getItemsByType("shortList")[3] 172 | firstItem == newList[3] && secondItem == newList[0] 173 | } 174 | 175 | adapter restructure { 176 | insertBottom { 177 | withItem(7.toShort()) 178 | withLayoutResId(android.R.layout.list_content) 179 | } 180 | insertTop { 181 | withItem(8.toShort()) 182 | withLayoutResId(android.R.layout.list_content) 183 | } 184 | } 185 | 186 | adapter update { 187 | swap(1, 4, "shortList") 188 | } 189 | 190 | assertTrue { 191 | val firstItem = adapter.getItemsByType("shortList")[1] 192 | val secondItem = adapter.getItemsByType("shortList")[4] 193 | firstItem == newList[4] && secondItem == newList[1] 194 | } 195 | } 196 | } -------------------------------------------------------------------------------- /library/src/test/java/com/link184/kidadapter/RecyclerViewActivity.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter 2 | 3 | import android.app.Activity 4 | import android.os.Bundle 5 | import androidx.recyclerview.widget.RecyclerView 6 | 7 | class RecyclerViewActivity : Activity() { 8 | val recyclerView by lazy { 9 | RecyclerView(this).apply { 10 | } 11 | } 12 | 13 | override fun onCreate(savedInstanceState: Bundle?) { 14 | super.onCreate(savedInstanceState) 15 | setContentView(recyclerView) 16 | recyclerView.measure(0, 0) 17 | recyclerView.layout(0, 0, 100, 10000) 18 | } 19 | } -------------------------------------------------------------------------------- /library/src/test/java/com/link184/kidadapter/RestructureTest.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter 2 | 3 | import android.R 4 | import android.os.Build 5 | import com.link184.kidadapter.exceptions.UndeclaredTag 6 | import com.link184.kidadapter.typed.AdapterViewTypeConfiguration 7 | import com.link184.kidadapter.typed.TypedKidAdapter 8 | import org.junit.Before 9 | import org.junit.FixMethodOrder 10 | import org.junit.Test 11 | import org.junit.runner.RunWith 12 | import org.junit.runners.MethodSorters 13 | import org.robolectric.Robolectric 14 | import org.robolectric.RobolectricTestRunner 15 | import org.robolectric.android.controller.ActivityController 16 | import org.robolectric.annotation.Config 17 | import kotlin.test.assertEquals 18 | import kotlin.test.assertFailsWith 19 | import kotlin.test.assertNotNull 20 | import kotlin.test.assertTrue 21 | 22 | @RunWith(RobolectricTestRunner::class) 23 | @Config(sdk = [Build.VERSION_CODES.UPSIDE_DOWN_CAKE]) 24 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 25 | class RestructureTest { 26 | private lateinit var activityController: ActivityController 27 | private lateinit var adapter: TypedKidAdapter 28 | private var oldListSize: Int = 0 29 | 30 | @Before 31 | fun setUp() { 32 | activityController = Robolectric.buildActivity(RecyclerViewActivity::class.java) 33 | adapter = setUpRecyclerView() 34 | oldListSize = adapter.itemCount 35 | } 36 | 37 | private fun setUpRecyclerView(): TypedKidAdapter { 38 | return activityController.get().recyclerView.setUp { 39 | withViewType { 40 | withItems(mutableListOf(1, 2, 3)) 41 | withLayoutResId(android.R.layout.list_content) 42 | bind { } 43 | } 44 | 45 | withViewType { 46 | withItems(mutableListOf(1.1, 2.2, 3.3)) 47 | withLayoutResId(android.R.layout.list_content) 48 | bind { } 49 | } 50 | 51 | withViewType { 52 | withItems(mutableListOf("one", "two", "three")) 53 | withLayoutResId(android.R.layout.list_content) 54 | bind { } 55 | } 56 | } 57 | } 58 | 59 | @Test 60 | fun t01_insertViewType() { 61 | val items = mutableListOf(4, 5, 6, 7) 62 | adapter restructure { 63 | insert(2, "tag") { 64 | withItems(items) 65 | withLayoutResId(android.R.layout.list_content) 66 | bind { 67 | println("We are here $it") 68 | } 69 | } 70 | } 71 | 72 | activityController.create().start().visible() 73 | 74 | assertTrue { 75 | adapter.itemCount != oldListSize && 76 | adapter.itemCount > oldListSize && 77 | adapter.itemCount == items.size + oldListSize 78 | } 79 | } 80 | 81 | @Test 82 | fun t02_insertTopViewType() { 83 | val items = mutableListOf("2", "3", "4") 84 | adapter restructure { 85 | insertTop { 86 | withItems(items) 87 | withLayoutResId(android.R.layout.list_content) 88 | bind { 89 | println("We are here $it") 90 | } 91 | } 92 | } 93 | 94 | assertTrue { 95 | adapter.itemCount != oldListSize && 96 | adapter.itemCount > oldListSize && 97 | adapter.itemCount == items.size + oldListSize 98 | } 99 | 100 | assertTrue { 101 | adapter[0] == "2" && 102 | adapter[1] == "3" && 103 | adapter[2] == "4" && 104 | adapter[3] == 1 105 | } 106 | } 107 | 108 | @Test 109 | fun t03_insertBottomViewType() { 110 | val items = mutableListOf(5.5, 6.6, 7.7) 111 | adapter restructure { 112 | insertBottom { 113 | withItems(items) 114 | withLayoutResId(android.R.layout.list_content) 115 | bind { 116 | println("We are here $it") 117 | } 118 | } 119 | } 120 | 121 | assertTrue { 122 | adapter.itemCount != oldListSize && 123 | adapter.itemCount > oldListSize && 124 | adapter.itemCount == items.size + oldListSize 125 | } 126 | 127 | assertTrue { 128 | adapter[adapter.itemCount - 1] == 7.7 && 129 | adapter[adapter.itemCount - 2] == 6.6 && 130 | adapter[adapter.itemCount - 3] == 5.5 131 | } 132 | } 133 | 134 | @Test 135 | fun t04_removeByTagViewType() { 136 | adapter restructure { 137 | insert(2, "myTag") { 138 | withItem("22") 139 | withLayoutResId(android.R.layout.list_content) 140 | bind { 141 | println("We are here $it") 142 | } 143 | } 144 | } 145 | 146 | assertTrue { 147 | adapter.itemCount != oldListSize && 148 | adapter.itemCount > oldListSize && 149 | adapter.itemCount == 1 + oldListSize 150 | } 151 | 152 | val newItem = adapter.getItemsByType("myTag").first() 153 | assertNotNull(newItem) 154 | assertEquals("22", newItem) 155 | 156 | adapter restructure { 157 | remove("myTag") 158 | } 159 | 160 | assertFailsWith { 161 | adapter.getItemsByType("myTag").first() 162 | } 163 | 164 | assertTrue { 165 | adapter.itemCount == oldListSize 166 | } 167 | } 168 | 169 | @Test 170 | fun t05_removeByIndexViewType() { 171 | adapter restructure { 172 | insert(2, "myTag") { 173 | withItem("22") 174 | withLayoutResId(android.R.layout.list_content) 175 | bind { 176 | println("We are here $it") 177 | } 178 | } 179 | } 180 | 181 | assertTrue { 182 | adapter.itemCount != oldListSize && 183 | adapter.itemCount > oldListSize && 184 | adapter.itemCount == 1 + oldListSize 185 | } 186 | 187 | val newItem = adapter.getItemsByType("myTag").first() 188 | assertNotNull(newItem) 189 | assertEquals("22", newItem) 190 | 191 | adapter restructure { 192 | remove(2) 193 | } 194 | 195 | assertFailsWith { 196 | adapter.getItemsByType("myTag").first() 197 | } 198 | 199 | assertTrue { 200 | adapter.itemCount == oldListSize 201 | } 202 | } 203 | 204 | @Test 205 | fun t06_removeAllViewType() { 206 | adapter.restructure { 207 | removeAll() 208 | } 209 | assertEquals(0, adapter.itemCount) 210 | } 211 | 212 | @Test 213 | fun t07_replaceByTagViewType() { 214 | adapter restructure { 215 | insertBottom("myTag") { 216 | withItem("22") 217 | withLayoutResId(android.R.layout.list_content) 218 | bind { 219 | println("We are here $it") 220 | } 221 | } 222 | } 223 | 224 | assertTrue { 225 | adapter.itemCount != oldListSize && 226 | adapter.itemCount > oldListSize && 227 | adapter.itemCount == 1 + oldListSize 228 | } 229 | 230 | val newItem = adapter.getItemsByType("myTag").first() 231 | assertNotNull(newItem) 232 | assertEquals("22", newItem) 233 | 234 | adapter restructure { 235 | replace("myTag") { 236 | withItem(44) 237 | withLayoutResId(android.R.layout.list_content) 238 | bind { 239 | println("We are here $it") 240 | } 241 | } 242 | } 243 | 244 | assertTrue { 245 | adapter.itemCount != oldListSize && 246 | adapter.itemCount > oldListSize && 247 | adapter.itemCount == 1 + oldListSize 248 | } 249 | 250 | val replacedItem = adapter.getItemsByType("myTag").first() 251 | assertNotNull(replacedItem) 252 | assertEquals(44, replacedItem) 253 | } 254 | 255 | @Test 256 | fun t08_replaceByIndexViewType() { 257 | adapter restructure { 258 | insert(2, "myTag") { 259 | withItem("22") 260 | withLayoutResId(android.R.layout.list_content) 261 | bind { 262 | println("We are here $it") 263 | } 264 | } 265 | } 266 | 267 | assertTrue { 268 | adapter.itemCount != oldListSize && 269 | adapter.itemCount > oldListSize && 270 | adapter.itemCount == 1 + oldListSize 271 | } 272 | 273 | val newItem = adapter.getItemsByType("myTag").first() 274 | assertNotNull(newItem) 275 | assertEquals("22", newItem) 276 | 277 | adapter restructure { 278 | replace(2, "myNewTag") { 279 | withItem(44) 280 | withLayoutResId(android.R.layout.list_content) 281 | bind { 282 | println("We are here $it") 283 | } 284 | } 285 | } 286 | 287 | assertTrue { 288 | adapter.itemCount != oldListSize && 289 | adapter.itemCount > oldListSize && 290 | adapter.itemCount == 1 + oldListSize 291 | } 292 | 293 | assertFailsWith { 294 | adapter.getItemsByType("myTag") 295 | } 296 | val replacedItem = adapter.getItemsByType("myNewTag").first() 297 | assertNotNull(replacedItem) 298 | assertEquals(44, replacedItem) 299 | 300 | adapter restructure { 301 | replace(2) { 302 | withItem(500) 303 | withLayoutResId(android.R.layout.list_content) 304 | bind { 305 | println("We are here $it") 306 | } 307 | } 308 | } 309 | 310 | assertTrue { 311 | adapter.itemCount != oldListSize && 312 | adapter.itemCount > oldListSize && 313 | adapter.itemCount == 1 + oldListSize 314 | } 315 | 316 | assertFailsWith { adapter.getItemsByType("myTag") } 317 | assertFailsWith { adapter.getItemsByType("myNewTag") } 318 | 319 | val veryReplacedItem: Int = adapter[6] as Int 320 | assertEquals(500, veryReplacedItem) 321 | } 322 | 323 | @Test 324 | fun t09_swapViewType() { 325 | adapter restructure { 326 | swap(0, 2) 327 | } 328 | 329 | assertTrue { 330 | oldListSize == adapter.itemCount && 331 | adapter[0] is String && 332 | adapter[adapter.itemCount - 1] is Int 333 | } 334 | } 335 | 336 | @Test 337 | fun t10_mixedRestructuringViewType() { 338 | val simpleViewType: AdapterViewTypeConfiguration.() -> Unit = { 339 | withItem(44) 340 | withLayoutResId(R.layout.list_content) 341 | bind { 342 | println("We are here $it") 343 | } 344 | } 345 | adapter restructure { 346 | insertTop("top1", simpleViewType) 347 | insert(3, "insertAt3", simpleViewType) 348 | insertBottom("bottom1", simpleViewType) 349 | replace("top1", simpleViewType) 350 | } 351 | 352 | assertTrue { 353 | oldListSize < adapter.itemCount && 354 | oldListSize + 3 == adapter.itemCount 355 | } 356 | assertEquals(44, adapter[adapter.itemCount - 1]) 357 | 358 | adapter restructure { 359 | insertBottom("bottom1", simpleViewType) 360 | insertBottom("bottom2", simpleViewType) 361 | insertBottom("bottom3", simpleViewType) 362 | insertBottom("bottom4", simpleViewType) 363 | insertBottom("bottom5", simpleViewType) 364 | removeAll() 365 | insertTop("top1", simpleViewType) 366 | } 367 | 368 | assertTrue { adapter.itemCount == 1 } 369 | assertEquals(44, adapter[0]) 370 | } 371 | } -------------------------------------------------------------------------------- /library/src/test/java/com/link184/kidadapter/SingleKidAdapterTest.kt: -------------------------------------------------------------------------------- 1 | package com.link184.kidadapter 2 | 3 | import android.os.Build 4 | import com.link184.kidadapter.simple.SingleKidAdapterConfiguration 5 | import org.junit.Before 6 | import org.junit.FixMethodOrder 7 | import org.junit.Test 8 | import org.junit.runner.RunWith 9 | import org.junit.runners.MethodSorters 10 | import org.mockito.ArgumentMatchers.anyInt 11 | import org.mockito.Mockito 12 | import org.mockito.internal.verification.VerificationModeFactory.times 13 | import org.robolectric.Robolectric 14 | import org.robolectric.RobolectricTestRunner 15 | import org.robolectric.android.controller.ActivityController 16 | import org.robolectric.annotation.Config 17 | import kotlin.test.assertEquals 18 | import kotlin.test.assertNotEquals 19 | import kotlin.test.assertTrue 20 | 21 | @RunWith(RobolectricTestRunner::class) 22 | @Config(sdk = [Build.VERSION_CODES.UPSIDE_DOWN_CAKE]) 23 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 24 | class SingleKidAdapterTest { 25 | lateinit var activityController: ActivityController 26 | @Before 27 | fun setUp() { 28 | activityController = Robolectric.buildActivity(RecyclerViewActivity::class.java) 29 | } 30 | 31 | @Test 32 | fun t1_simpleAdapterPopulateTest() { 33 | val items = mutableListOf("a", "b", "c", "d") 34 | val bindFunction: SingleKidAdapterConfiguration.(String) -> Unit = { println(it) } 35 | val bindFunctionIndexed: SingleKidAdapterConfiguration.(String, Int) -> Unit = { item, index -> 36 | println("$item $index") 37 | } 38 | val bindFunctionSpy = spy(bindFunction) 39 | val bindIndexedFunctionSpy = spy(bindFunctionIndexed) 40 | 41 | activityController.get().recyclerView.setUp { 42 | withItems(items) 43 | withLayoutResId(android.R.layout.list_content) 44 | bindIndexed { item, index -> 45 | assertTrue(items.contains(item)) 46 | bindIndexedFunctionSpy(item, index) 47 | } 48 | bind { 49 | assertTrue(items.contains(it)) 50 | bindFunctionSpy(it) 51 | } 52 | } 53 | 54 | activityController.create().start().visible() 55 | Mockito.verify(bindFunctionSpy, times(items.size)).invoke(anyNullableObject(), anyNullableObject()) 56 | Mockito.verify(bindIndexedFunctionSpy, times(items.size)) 57 | .invoke(anyNullableObject(), anyNullableObject(), anyInt()) 58 | } 59 | 60 | @Test 61 | fun t2_operationsTest() { 62 | val items = mutableListOf(1, 2, 3, 4, 5) 63 | val initialItemsSize = items.size 64 | 65 | val adapter = activityController.get().recyclerView.setUp { 66 | withItems(items) 67 | withLayoutResId(android.R.layout.list_content) 68 | bindIndexed { item, index -> 69 | assertTrue(items.contains(item)) 70 | } 71 | bind { 72 | assertTrue(items.contains(it)) 73 | } 74 | } 75 | 76 | adapter + 6 + 7 + 8 77 | assertEquals(items.size, initialItemsSize + 3) 78 | 79 | adapter + 9 - 4 - 1 80 | assertEquals(items.size, initialItemsSize + 3 + 1 - 2) 81 | assertTrue { 82 | !items.contains(1) 83 | !items.contains(4) 84 | } 85 | } 86 | 87 | @Test 88 | fun t3_updateAdapterTest() { 89 | val items = mutableListOf(1, 2, 3, 4, 5) 90 | val initialItemsSize = items.size 91 | 92 | val bindFunction: SingleKidAdapterConfiguration.(Int) -> Unit = { println(it) } 93 | val bindFunctionSpy = spy(bindFunction) 94 | 95 | val adapter = activityController.get().recyclerView.setUp { 96 | withItems(items) 97 | withLayoutResId(android.R.layout.list_content) 98 | bindIndexed { item, index -> 99 | assertTrue(items.contains(item)) 100 | } 101 | bind { 102 | assertTrue(items.contains(it)) 103 | bindFunctionSpy(it) 104 | } 105 | } 106 | 107 | activityController.create().start().visible() 108 | 109 | Mockito.verify(bindFunctionSpy, times(initialItemsSize)).invoke(anyNullableObject(), anyInt()) 110 | 111 | adapter update { 112 | it.add(6) 113 | it.add(7) 114 | it.remove(2) 115 | it[0] = 1 116 | } 117 | 118 | activityController.create().start().visible() 119 | 120 | Mockito.verify(bindFunctionSpy, times(initialItemsSize + 3)).invoke(anyNullableObject(), anyInt()) 121 | assertNotEquals(initialItemsSize, adapter.itemCount) 122 | assertTrue { adapter.getAllItems().indexOf(3) == 1 } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /library/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker: -------------------------------------------------------------------------------- 1 | mock-maker-inline -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Link184/KidAdapter/a922f8382f5b5957ddbf15a09f48c1d27b99b874/logo.png -------------------------------------------------------------------------------- /publish.gradle: -------------------------------------------------------------------------------- 1 | ext { 2 | ext.resolveRepositoyUrl = { 3 | if (isReleaseBuild()) { 4 | return "https://oss.sonatype.org/service/local/staging/deploy/maven2/" 5 | } else { 6 | return "https://oss.sonatype.org/content/repositories/snapshots/" 7 | } 8 | } 9 | 10 | ext.getUsername = { 11 | if (hasProperty('SONATYPE_NEXUS_USERNAME')) { 12 | return SONATYPE_NEXUS_USERNAME 13 | } 14 | 15 | def propertiesFile = project.rootProject.file('local.properties') 16 | if (propertiesFile.exists()) { 17 | Properties properties = new Properties() 18 | properties.load(propertiesFile.newDataInputStream()) 19 | return properties.getProperty('SONATYPE_NEXUS_USERNAME') 20 | } else { 21 | return "" 22 | } 23 | } 24 | 25 | ext.getPassword = { 26 | if (hasProperty('SONATYPE_NEXUS_PASSWORD')) { 27 | return SONATYPE_NEXUS_PASSWORD 28 | } 29 | 30 | def propertiesFile = project.rootProject.file('local.properties') 31 | if (propertiesFile.exists()) { 32 | Properties properties = new Properties() 33 | properties.load(propertiesFile.newDataInputStream()) 34 | return properties.getProperty('SONATYPE_NEXUS_PASSWORD') 35 | } else { 36 | return "" 37 | } 38 | } 39 | } 40 | 41 | def isReleaseBuild() { 42 | return !VERSION_NAME.contains("SNAPSHOT") 43 | } 44 | -------------------------------------------------------------------------------- /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | android { 4 | compileSdk 35 5 | 6 | defaultConfig { 7 | applicationId "com.link184.sample" 8 | minSdkVersion 21 9 | targetSdk 35 10 | versionCode 1 11 | versionName "1.0" 12 | 13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 14 | 15 | } 16 | 17 | compileOptions { 18 | sourceCompatibility = JavaVersion.VERSION_1_8 19 | targetCompatibility = JavaVersion.VERSION_1_8 20 | } 21 | 22 | kotlinOptions { 23 | jvmTarget = "1.8" 24 | } 25 | 26 | buildTypes { 27 | release { 28 | minifyEnabled false 29 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 30 | } 31 | } 32 | namespace 'com.link184.sample' 33 | } 34 | 35 | repositories { 36 | maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } 37 | mavenLocal() 38 | } 39 | 40 | dependencies { 41 | implementation fileTree(dir: 'libs', include: ['*.jar']) 42 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 43 | implementation 'androidx.appcompat:appcompat:1.7.0' 44 | testImplementation 'junit:junit:4.13.2' 45 | testImplementation "org.jetbrains.kotlin:kotlin-test:$kotlin_version" 46 | 47 | androidTestImplementation 'junit:junit:4.13.2' 48 | androidTestImplementation 'androidx.test:runner:1.6.2' 49 | 50 | implementation 'com.link184:common-extensions:1.0.3' 51 | // implementation 'com.link184:lifecycle-delegates:1.0.3-SNAPSHOT' 52 | implementation 'com.link184:kid-adapter:1.4.0-SNAPSHOT' 53 | 54 | // implementation project(':library') 55 | } 56 | -------------------------------------------------------------------------------- /sample/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /sample/src/main/java/com/link184/sample/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.link184.sample 2 | 3 | import android.content.Intent 4 | import android.os.Bundle 5 | import android.view.View 6 | import androidx.appcompat.app.AppCompatActivity 7 | 8 | class MainActivity : AppCompatActivity() { 9 | 10 | override fun onCreate(savedInstanceState: Bundle?) { 11 | super.onCreate(savedInstanceState) 12 | setContentView(R.layout.activity_main) 13 | 14 | findViewById(R.id.multiTypeButton).setOnClickListener { startActivity(Intent(this, MultiTypeActivity::class.java)) } 15 | findViewById(R.id.singleTypeButton).setOnClickListener { startActivity(Intent(this, SingleTypeActivity::class.java)) } 16 | findViewById(R.id.multiTypeWithTagsButton).setOnClickListener { startActivity(Intent(this, MultiTypeWithTagsActivity::class.java)) } 17 | findViewById(R.id.viewPager2Adapter).setOnClickListener { startActivity(Intent(this, ViewPagerActivity::class.java)) } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /sample/src/main/java/com/link184/sample/MultiTypeActivity.kt: -------------------------------------------------------------------------------- 1 | package com.link184.sample 2 | 3 | import android.os.Bundle 4 | import android.widget.TextView 5 | import android.widget.Toast 6 | import androidx.appcompat.app.AppCompatActivity 7 | import androidx.recyclerview.widget.DividerItemDecoration 8 | import androidx.recyclerview.widget.RecyclerView 9 | import com.link184.kidadapter.setUp 10 | 11 | class MultiTypeActivity : AppCompatActivity() { 12 | 13 | override fun onCreate(savedInstanceState: Bundle?) { 14 | super.onCreate(savedInstanceState) 15 | setContentView(R.layout.activity_multi_type) 16 | 17 | with(findViewById(R.id.recyclerView)) { 18 | addItemDecoration( 19 | DividerItemDecoration( 20 | this@MultiTypeActivity, 21 | DividerItemDecoration.VERTICAL 22 | ) 23 | ) 24 | 25 | setUp { 26 | withViewType { 27 | withLayoutResId(R.layout.item_text) 28 | withItems( 29 | mutableListOf( 30 | "one", 31 | "two", 32 | "three", 33 | "four", 34 | "five", 35 | "six", 36 | "seven" 37 | ) 38 | ) 39 | bindIndexed { item, position -> 40 | findViewById(R.id.stringName).text = item 41 | setOnClickListener { 42 | Toast.makeText(context, position.toString(), Toast.LENGTH_SHORT) 43 | .show() 44 | } 45 | } 46 | } 47 | 48 | withViewType { 49 | withLayoutResId(R.layout.item_int) 50 | withItems(mutableListOf(8, 9, 10, 11, 12, 13)) 51 | bindIndexed { item, position -> 52 | findViewById(R.id.intName).text = item.toString() 53 | setOnClickListener { 54 | Toast.makeText(context, position.toString(), Toast.LENGTH_SHORT) 55 | .show() 56 | } 57 | } 58 | } 59 | } 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /sample/src/main/java/com/link184/sample/MultiTypeWithTagsActivity.kt: -------------------------------------------------------------------------------- 1 | package com.link184.sample 2 | 3 | import android.os.Bundle 4 | import android.widget.TextView 5 | import android.widget.Toast 6 | import androidx.appcompat.app.AppCompatActivity 7 | import androidx.recyclerview.widget.DividerItemDecoration 8 | import androidx.recyclerview.widget.RecyclerView 9 | import com.link184.kidadapter.setUp 10 | 11 | private const val FIRST_STRING_TAG = "first_string_tag" 12 | private const val SECOND_STRING_TAG = "second_string_tag" 13 | 14 | class MultiTypeWithTagsActivity : AppCompatActivity() { 15 | 16 | override fun onCreate(savedInstanceState: Bundle?) { 17 | super.onCreate(savedInstanceState) 18 | setContentView(R.layout.activity_multi_type_with_tags) 19 | val recyclerView = findViewById(R.id.recyclerView) 20 | recyclerView.addItemDecoration( 21 | DividerItemDecoration( 22 | this, 23 | DividerItemDecoration.VERTICAL 24 | ) 25 | ) 26 | val adapter = recyclerView.setUp { 27 | withViewType(FIRST_STRING_TAG) { 28 | withLayoutResId(R.layout.item_text) 29 | withItems(mutableListOf("one", "two", "three", "four", "five", "six", "seven")) 30 | bindIndexed { item, position -> 31 | findViewById(R.id.stringName).text = item 32 | setOnClickListener { 33 | Toast.makeText(context, position.toString(), Toast.LENGTH_SHORT).show() 34 | } 35 | } 36 | } 37 | withViewType { 38 | withLayoutResId(R.layout.item_int) 39 | withItems(mutableListOf(1, 2, 3, 4, 5, 6)) 40 | bindIndexed { item, position -> 41 | findViewById(R.id.intName).text = item.toString() 42 | setOnClickListener { 43 | Toast.makeText(context, position.toString(), Toast.LENGTH_SHORT).show() 44 | } 45 | } 46 | } 47 | 48 | withViewType(SECOND_STRING_TAG) { 49 | withLayoutResId(R.layout.item_text) 50 | withItems(mutableListOf("eight", "nine", "ten", "eleven", "twelve")) 51 | bindIndexed { item, position -> 52 | findViewById(R.id.stringName).text = item 53 | setOnClickListener { 54 | Toast.makeText(context, position.toString(), Toast.LENGTH_SHORT).show() 55 | } 56 | } 57 | } 58 | } 59 | 60 | recyclerView.postDelayed({ 61 | adapter update { 62 | insertBottom(mutableListOf("thirteen", "fourteen"), SECOND_STRING_TAG) 63 | } 64 | }, 2_000) 65 | 66 | recyclerView.postDelayed({ 67 | adapter update { 68 | removeItems(mutableListOf(2, 4, 5)) 69 | } 70 | }, 4_000) 71 | 72 | recyclerView.postDelayed({ 73 | adapter update { 74 | insert(2, mutableListOf("New String 1", "New String 2"), FIRST_STRING_TAG) 75 | } 76 | }, 6_000) 77 | 78 | recyclerView.postDelayed({ 79 | adapter update { 80 | swap(2, 4, FIRST_STRING_TAG) 81 | } 82 | }, 8_000) 83 | 84 | recyclerView.postDelayed({ 85 | adapter update { 86 | removeAll() 87 | removeAll() 88 | removeAll(SECOND_STRING_TAG) 89 | } 90 | }, 14_000) 91 | } 92 | } -------------------------------------------------------------------------------- /sample/src/main/java/com/link184/sample/SingleTypeActivity.kt: -------------------------------------------------------------------------------- 1 | package com.link184.sample 2 | 3 | import android.graphics.Color 4 | import android.os.Bundle 5 | import android.widget.TextView 6 | import android.widget.Toast 7 | import androidx.appcompat.app.AppCompatActivity 8 | import androidx.recyclerview.widget.RecyclerView 9 | import com.link184.kidadapter.setUp 10 | import java.util.Random 11 | 12 | class SingleTypeActivity : AppCompatActivity() { 13 | 14 | override fun onCreate(savedInstanceState: Bundle?) { 15 | super.onCreate(savedInstanceState) 16 | setContentView(R.layout.activity_single_type) 17 | 18 | val recyclerView = findViewById(R.id.recyclerView) 19 | val adapter = recyclerView.setUp { 20 | withLayoutResId(R.layout.item_text) 21 | withItems(mutableListOf("one", "two", "three", "four", "five", "six", "seven")) 22 | bindIndexed { item, position -> 23 | setBackgroundColor(getRandomColor()) 24 | findViewById(R.id.stringName).text = item 25 | setOnClickListener { 26 | Toast.makeText(context, position.toString(), Toast.LENGTH_SHORT).show() 27 | } 28 | } 29 | } 30 | 31 | 32 | recyclerView.postDelayed({ adapter + "1" }, 2_000) 33 | recyclerView.postDelayed({ adapter + mutableListOf("2", "3", "4") }, 4_000) 34 | recyclerView.postDelayed({ adapter[2] = "3" }, 4_000) 35 | recyclerView.postDelayed({ adapter.clear() }, 8_000) 36 | } 37 | 38 | private fun getRandomColor(): Int { 39 | val rnd = Random(System.nanoTime()) 40 | return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /sample/src/main/java/com/link184/sample/ViewPagerActivity.kt: -------------------------------------------------------------------------------- 1 | package com.link184.sample 2 | 3 | import android.os.Bundle 4 | import android.widget.TextView 5 | import androidx.appcompat.app.AppCompatActivity 6 | import androidx.viewpager2.widget.ViewPager2 7 | import com.link184.kidadapter.setUp 8 | 9 | class ViewPagerActivity: AppCompatActivity() { 10 | override fun onCreate(savedInstanceState: Bundle?) { 11 | super.onCreate(savedInstanceState) 12 | setContentView(R.layout.activity_view_pager) 13 | 14 | findViewById(R.id.viewPager).setUp { 15 | withItems(mutableListOf("one", "two", "three")) 16 | withLayoutResId(R.layout.view_tab) 17 | bind { findViewById(R.id.name).text = it } 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /sample/src/main/res/anim/item_fall_down_high.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 14 | 15 | 23 | 24 | -------------------------------------------------------------------------------- /sample/src/main/res/anim/item_fall_down_low.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 14 | 15 | 23 | 24 | -------------------------------------------------------------------------------- /sample/src/main/res/anim/item_fall_down_medium.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 14 | 15 | 23 | 24 | -------------------------------------------------------------------------------- /sample/src/main/res/anim/item_rise_up_high.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 14 | 15 | 23 | 24 | -------------------------------------------------------------------------------- /sample/src/main/res/anim/item_rise_up_medium.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 14 | 15 | 23 | 24 | -------------------------------------------------------------------------------- /sample/src/main/res/anim/item_scale_up_rotation_medium.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | 19 | 20 | 29 | 30 | 38 | -------------------------------------------------------------------------------- /sample/src/main/res/anim/item_slide_right_high.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 14 | 15 | -------------------------------------------------------------------------------- /sample/src/main/res/anim/item_slide_right_medium.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 14 | 15 | -------------------------------------------------------------------------------- /sample/src/main/res/anim/layout_fall_down_high.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /sample/src/main/res/anim/layout_fall_down_low.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /sample/src/main/res/anim/layout_fall_down_medium.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /sample/src/main/res/anim/layout_rise_up_high.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /sample/src/main/res/anim/layout_rise_up_medium.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /sample/src/main/res/anim/layout_scale_up_rotation_medium.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /sample/src/main/res/anim/layout_slide_right_high.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /sample/src/main/res/anim/layout_slide_right_medium.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34 | 36 | 38 | 40 | 42 | 44 | 46 | 48 | 50 | 52 | 54 | 56 | 58 | 60 | 62 | 64 | 66 | 68 | 70 | 72 | 74 | 75 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 |