├── .github └── workflows │ ├── merge_request.yml │ └── publish.yml ├── .gitignore ├── LICENSE.txt ├── README.md ├── build.gradle ├── changelog.md ├── demo ├── build.gradle └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── ru │ │ └── tinkoff │ │ └── scrollingpagerindicator │ │ └── demo │ │ ├── DemoPagerAdapter.java │ │ ├── DemoRecyclerViewAdapter.java │ │ └── MainActivity.java │ └── res │ ├── drawable-v24 │ └── ic_launcher_foreground.xml │ ├── drawable │ ├── baseline_accessibility_new_24.xml │ ├── baseline_free_breakfast_24.xml │ └── ic_launcher_background.xml │ ├── layout │ ├── activity_main.xml │ └── demo_page.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 │ ├── dimen.xml │ ├── strings.xml │ └── styles.xml ├── gradle.properties ├── gradle ├── publish-lib.gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── readmeAssets ├── custom-drawables.gif ├── demo-horizontal.gif └── demo.gif ├── scrollingpagerindicator ├── build.gradle ├── gradle.properties └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── ru │ │ └── tinkoff │ │ └── scrollingpagerindicator │ │ ├── AbstractViewPagerAttacher.java │ │ ├── RecyclerViewAttacher.java │ │ ├── ScrollingPagerIndicator.java │ │ ├── ViewPager2Attacher.java │ │ └── ViewPagerAttacher.java │ └── res │ └── values │ ├── attrs.xml │ └── styles.xml └── settings.gradle /.github/workflows/merge_request.yml: -------------------------------------------------------------------------------- 1 | name: merge request 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - 'master' 7 | 8 | jobs: 9 | check: 10 | uses: tinkoff-mobile-tech/workflows/.github/workflows/android_lib.merge_request.yml@v1 -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: publish 2 | 3 | on: 4 | workflow_dispatch: 5 | 6 | jobs: 7 | publish: 8 | uses: tinkoff-mobile-tech/workflows/.github/workflows/android_lib.publish.yml@v1 9 | secrets: 10 | gpg_key: ${{ secrets.GPG_KEY }} 11 | sign_ossrh_gradle_properties: ${{ secrets.SIGN_OSSRH_GRADLE_PROPERTIES }} 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle/ 2 | .idea/ 3 | build/ 4 | captures/ 5 | *.iml 6 | local.properties 7 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Maven Central][img version shield]][maven] 2 | 3 | ScrollingPagerIndicator 4 | ======================= 5 | Pager indicator inspired by Instagram. Lightweight and easy to set up. 6 | 7 | Supports ViewPager, RecyclerView and attaching to custom pagers. 8 | 9 | ![preview](readmeAssets/demo.gif) 10 | ![preview](readmeAssets/demo-horizontal.gif) 11 | ![Custom drawables](readmeAssets/custom-drawables.gif) 12 | 13 | ## Getting started 14 | Add dependency to Gradle script: 15 | ```Groovy 16 | implementation "ru.tinkoff.scrollingpagerindicator:scrollingpagerindicator:x.x.x" 17 | ``` 18 | ## Attach to ViewPager 19 | 1. Ensure that you have ViewPager in dependencies: 20 | ``` 21 | implementation "androidx.viewpager:viewpager:x.x.x" 22 | ``` 23 | or 24 | ``` 25 | implementation "androidx.viewpager2:viewpager2:x.x.x" 26 | ``` 27 | or 28 | ``` 29 | implementation "androidx.recyclerview:recyclerview:x.x.x" 30 | ``` 31 | 2. Add view to layout: 32 | ```xml 33 | 37 | 38 | 42 | ``` 43 | There is no possibility to set fixed indicator width (because it's width is based on ```spi_visibleDotCount```). 44 | 45 | 3. Attach indicator to ViewPager: 46 | ```java 47 | ViewPager pager = findViewById(R.id.pager); 48 | pager.setAdapter(new DemoPagerAdapter()); 49 | ScaledDotsIndicator indicator = findViewById(R.id.indicator); 50 | indicator.attachToPager(pager); 51 | ``` 52 | ## Attach to RecyclerView 53 | 1. Ensure that you have RecyclerView in dependencies: 54 | ``` 55 | implementation "androidx.recyclerview:recyclerview:x.x.x" 56 | ``` 57 | 2. Add view to layout: 58 | ```xml 59 | 63 | 64 | 68 | ``` 69 | 3. Attach indicator to RecyclerView: 70 | ```java 71 | RecyclerView recyclerView = findViewById(R.id.recycler); 72 | LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); 73 | recyclerView.setLayoutManager(layoutManager); 74 | DemoRecyclerViewAdapter recyclerAdapter = new DemoRecyclerViewAdapter(); 75 | recyclerView.setAdapter(recyclerAdapter); 76 | 77 | ScrollingPagerIndicator recyclerIndicator = findViewById(R.id.indicator); 78 | recyclerIndicator.attachToRecyclerView(recyclerView); 79 | ``` 80 | 4. Determine which page is current in RecyclerView: 81 | 82 | Use ```attachToRecyclerView(RecyclerView)``` if current page of the recycler is centered. 83 | Like this: 84 | ``` 85 | +------------------------------+ 86 | |---+ +----------------+ +---| 87 | | | | current | | | 88 | | | | page | | | 89 | |---+ +----------------+ +---| 90 | +------------------------------+ 91 | ``` 92 | Use ```attachToRecyclerView(RecyclerView recyclerView, int currentPageLeftCornerX)``` if current page of the recycler isn't centered. Like this: 93 | ``` 94 | +-|----------------------------+ 95 | | +--------+ +--------+ +----+ 96 | | | current| | | | | 97 | | | page | | | | | 98 | | +--------+ +--------+ +----| 99 | +-|----------------------------+ 100 | | 101 | | currentPageLeftCornerX 102 | ``` 103 | In both cases all views in RecyclerView must have the same width. Only ```LinearLayoutManager``` is supported. 104 | ## Attach to any custom pager 105 | If you want to attach indicator to some custom pager, you have to implement ```ScrollingPagerIndicator.PagerAttacher``` interface. 106 | You can take look at ```ru.tinkoff.scrollingpagerindicator.ViewPagerAttacher``` as implementation example. 107 | And then you can attach your pager like this: 108 | ```java 109 | indicator.attachToPager(pager, new ViewPagerAttacher()); 110 | ``` 111 | ## Customization 112 | | Attribute | Explanation | Default Value | 113 | |-------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------| 114 | | spi_dotSize | The diameter of a dot. | ```6dp``` | 115 | | spi_dotSelectedSize | The diameter of a currently selected dot. | ```10dp``` | 116 | | spi_dotColor | The color of a dot. | ```@android:color/darker_gray``` | 117 | | spi_dotSelectedColor | The color of the currently selected dot. | ```@android:color/darker_gray``` | 118 | | spi_dotSpacing | The distance from center to center of each dot. | ```8dp``` | 119 | | spi_visibleDotCount | The maximum number of dots which will be visible at the same time. If pager has more pages than visible_dot_count, indicator will scroll to show extra dots. Must be odd number. | ```5``` | 120 | | spi_visibleDotThreshold | The minimum number of dots which should be visible. If pager has less pages than visibleDotThreshold, no dots will be shown. | ```2``` | 121 | | spi_looped | The mode for looped pagers support. You should make indicator looped if your custom pager is looped too. If pager has less items than ```spi_visibleDotCount```, indicator will work as usual; otherwise it will always be in infinite state. | ```false``` | 122 | | spi_dotMinimumSize | The minimum dot size for the corner dots. This size is lower or equal to ```spi_dotSize``` and greater or equal to the internal calculation for the corner dots. | Internal calculation based on ```spi_dotSize```, ```spi_dotSelectedSize``` and ```spi_dotSpacing``` | 123 | | spi_orientation | Visible orientation of the dots | LinearLayoutManager.HORIZONTAL | 124 | | spi_firstDotDrawable | Custom drawable of the first dot, color is tinted and size is changed like standard dots. If first dot is also the last one then this value is taken into account. | `null` | 125 | | spi_lastDotDrawable | Custom drawable of the last dot, color is tinted and size is changed like standard dots. | `null` | 126 | 127 | ## TODO 128 | 1. Some extreme customizations may work incorrect. 129 | 2. There is no possibility to set fixed indicator width (because it's width is based on ```spi_visibleDotCount```). 130 | 131 | ## License 132 | ``` 133 | Copyright 2018 Tinkoff Bank 134 | 135 | Licensed under the Apache License, Version 2.0 (the "License"); 136 | you may not use this file except in compliance with the License. 137 | You may obtain a copy of the License at 138 | 139 | http://www.apache.org/licenses/LICENSE-2.0 140 | 141 | Unless required by applicable law or agreed to in writing, software 142 | distributed under the License is distributed on an "AS IS" BASIS, 143 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 144 | See the License for the specific language governing permissions and 145 | limitations under the License. 146 | ``` 147 | [img version shield]: https://img.shields.io/maven-central/v/ru.tinkoff.scrollingpagerindicator/scrollingpagerindicator.svg?maxAge=3600 148 | [maven]: https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22ru.tinkoff.scrollingpagerindicator%22 149 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | def useMavenLocal = project.hasProperty("useMavenLocal") 2 | 3 | buildscript { 4 | 5 | repositories { 6 | google() 7 | mavenCentral() 8 | } 9 | dependencies { 10 | classpath 'com.android.tools.build:gradle:7.4.2' 11 | } 12 | } 13 | 14 | allprojects { 15 | repositories { 16 | if (useMavenLocal) mavenLocal() 17 | google() 18 | mavenCentral() 19 | } 20 | } 21 | 22 | task clean(type: Delete) { 23 | delete rootProject.buildDir 24 | } 25 | 26 | ext { 27 | minSdk = 14 28 | compileSdk = 33 29 | targetSdk = 33 30 | 31 | isRelease = project.hasProperty('release') 32 | versionName = isRelease ? VERSION_NAME : "$VERSION_NAME-SNAPSHOT" 33 | 34 | appCompatVersion = "1.6.1" 35 | constraintLayoutVersion = "2.1.4" 36 | viewPagerVersion = "1.0.0" 37 | viewPager2Version = "1.0.0" 38 | cardViewVersion = "1.0.0" 39 | recyclerViewVersion = "1.3.0" 40 | } 41 | -------------------------------------------------------------------------------- /changelog.md: -------------------------------------------------------------------------------- 1 | ## 1.2.4 2 | - Add support for custom first and last page indicators 3 | 4 | ## 1.2.3 5 | - updated target sdk version to 31 6 | 7 | ## 1.2.2 8 | 9 | #### Fixes 10 | - support RTL direction in horizontal mode when the view is RTL [#29](https://github.com/Tinkoff/ScrollingPagerIndicator/issues/29) 11 | - turn off RTL direction by `setAutoRtl(false)` 12 | 13 | #### Changes 14 | #### Additions 15 | 16 | ## 1.2.1 17 | 18 | #### Fixes 19 | #### Changes 20 | -[scrollingpagerindicator] updated android gradle plugin to 3.6.4 21 | -[scrollingpagerindicator] changed publishing plugin to maven-publish 22 | #### Additions 23 | -------------------------------------------------------------------------------- /demo/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | namespace "ru.tinkoff.scrollingpagerindicator.demo" 5 | compileSdkVersion rootProject.compileSdk 6 | 7 | defaultConfig { 8 | applicationId "ru.tinkoff.scrollingpagerindicator.demo" 9 | minSdkVersion rootProject.minSdk 10 | targetSdkVersion rootProject.targetSdk 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | compileOptions { 15 | sourceCompatibility JavaVersion.VERSION_1_8 16 | targetCompatibility JavaVersion.VERSION_1_8 17 | } 18 | } 19 | 20 | dependencies { 21 | implementation "androidx.appcompat:appcompat:$rootProject.appCompatVersion" 22 | implementation "androidx.constraintlayout:constraintlayout:$rootProject.constraintLayoutVersion" 23 | implementation "androidx.viewpager:viewpager:$rootProject.viewPagerVersion" 24 | implementation "androidx.viewpager2:viewpager2:$rootProject.viewPager2Version" 25 | implementation "androidx.cardview:cardview:$rootProject.cardViewVersion" 26 | implementation "androidx.recyclerview:recyclerview:$rootProject.recyclerViewVersion" 27 | implementation project(':scrollingpagerindicator') 28 | } 29 | -------------------------------------------------------------------------------- /demo/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 13 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /demo/src/main/java/ru/tinkoff/scrollingpagerindicator/demo/DemoPagerAdapter.java: -------------------------------------------------------------------------------- 1 | package ru.tinkoff.scrollingpagerindicator.demo; 2 | 3 | import android.view.LayoutInflater; 4 | import android.view.View; 5 | import android.view.ViewGroup; 6 | import android.widget.TextView; 7 | 8 | import androidx.annotation.NonNull; 9 | import androidx.viewpager.widget.PagerAdapter; 10 | 11 | /** 12 | * @author Nikita Olifer 13 | */ 14 | class DemoPagerAdapter extends PagerAdapter { 15 | private int pageCount; 16 | 17 | DemoPagerAdapter(int pageCount) { 18 | this.pageCount = pageCount; 19 | } 20 | 21 | void setCount(int count) { 22 | this.pageCount = count; 23 | notifyDataSetChanged(); 24 | } 25 | 26 | @NonNull 27 | @Override 28 | public Object instantiateItem(@NonNull ViewGroup collection, int position) { 29 | ViewGroup layout = (ViewGroup) LayoutInflater.from(collection.getContext()) 30 | .inflate(R.layout.demo_page, collection, false); 31 | TextView label = layout.findViewById(R.id.demo_page_label); 32 | label.setText(String.valueOf(position)); 33 | collection.addView(layout); 34 | return layout; 35 | } 36 | 37 | @Override 38 | public void destroyItem(@NonNull ViewGroup collection, int position, @NonNull Object view) { 39 | collection.removeView((View) view); 40 | } 41 | 42 | @Override 43 | public int getCount() { 44 | return pageCount; 45 | } 46 | 47 | @Override 48 | public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { 49 | return view == object; 50 | } 51 | 52 | @Override 53 | public int getItemPosition(@NonNull Object object) { 54 | return PagerAdapter.POSITION_NONE; 55 | } 56 | 57 | @Override 58 | public CharSequence getPageTitle(int position) { 59 | return String.valueOf(position); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /demo/src/main/java/ru/tinkoff/scrollingpagerindicator/demo/DemoRecyclerViewAdapter.java: -------------------------------------------------------------------------------- 1 | package ru.tinkoff.scrollingpagerindicator.demo; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.view.LayoutInflater; 5 | import android.view.View; 6 | import android.view.ViewGroup; 7 | import android.widget.TextView; 8 | 9 | import androidx.annotation.NonNull; 10 | import androidx.recyclerview.widget.RecyclerView; 11 | 12 | /** 13 | * @author Nikita Olifer 14 | */ 15 | public class DemoRecyclerViewAdapter extends RecyclerView.Adapter { 16 | 17 | private int count; 18 | private final int itemWidth; 19 | 20 | DemoRecyclerViewAdapter(int count, int itemWidth) { 21 | this.count = count; 22 | this.itemWidth = itemWidth; 23 | } 24 | 25 | @SuppressLint("NotifyDataSetChanged") 26 | void setCount(int count) { 27 | this.count = count; 28 | notifyDataSetChanged(); 29 | } 30 | 31 | @NonNull 32 | @Override 33 | public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 34 | View view = LayoutInflater.from(parent.getContext()) 35 | .inflate(R.layout.demo_page, parent, false); 36 | view.getLayoutParams().width = itemWidth; 37 | return new ViewHolder(view); 38 | } 39 | 40 | @Override 41 | public void onBindViewHolder(ViewHolder holder, int position) { 42 | holder.title.setText(String.valueOf(position)); 43 | } 44 | 45 | @Override 46 | public int getItemCount() { 47 | return count; 48 | } 49 | 50 | static class ViewHolder extends RecyclerView.ViewHolder { 51 | 52 | final TextView title; 53 | 54 | ViewHolder(View itemView) { 55 | super(itemView); 56 | title = itemView.findViewById(R.id.demo_page_label); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /demo/src/main/java/ru/tinkoff/scrollingpagerindicator/demo/MainActivity.java: -------------------------------------------------------------------------------- 1 | package ru.tinkoff.scrollingpagerindicator.demo; 2 | 3 | import android.content.Context; 4 | import android.graphics.Point; 5 | import android.os.Bundle; 6 | import android.view.Display; 7 | import android.view.ViewGroup; 8 | import android.view.WindowManager; 9 | import android.widget.NumberPicker; 10 | import android.widget.Toast; 11 | 12 | import androidx.appcompat.app.AppCompatActivity; 13 | import androidx.recyclerview.widget.LinearLayoutManager; 14 | import androidx.recyclerview.widget.PagerSnapHelper; 15 | import androidx.recyclerview.widget.RecyclerView; 16 | import androidx.recyclerview.widget.SnapHelper; 17 | import androidx.viewpager.widget.ViewPager; 18 | import androidx.viewpager2.widget.ViewPager2; 19 | 20 | import ru.tinkoff.scrollingpagerindicator.ScrollingPagerIndicator; 21 | 22 | public class MainActivity extends AppCompatActivity { 23 | 24 | @Override 25 | protected void onCreate(Bundle savedInstanceState) { 26 | super.onCreate(savedInstanceState); 27 | setContentView(R.layout.activity_main); 28 | 29 | int screenWidth = getScreenWidth(); 30 | 31 | // Setup ViewPager with indicator 32 | ViewPager pager = findViewById(R.id.pager); 33 | DemoPagerAdapter pagerAdapter = new DemoPagerAdapter(8); 34 | pager.setAdapter(pagerAdapter); 35 | 36 | ScrollingPagerIndicator pagerIndicator = findViewById(R.id.pager_indicator); 37 | pagerIndicator.attachToPager(pager); 38 | 39 | // Setup ViewPager2 with indicator 40 | ViewPager2 pager2 = findViewById(R.id.pager2); 41 | DemoRecyclerViewAdapter pagerAdapter2 = new DemoRecyclerViewAdapter(8, ViewGroup.LayoutParams.MATCH_PARENT); 42 | pager2.setAdapter(pagerAdapter2); 43 | 44 | ScrollingPagerIndicator pagerIndicator2 = findViewById(R.id.pager_indicator2); 45 | pagerIndicator2.attachToPager(pager2); 46 | 47 | // Setup RecyclerView with indicator 48 | // One page will occupy 1/3 of screen width 49 | RecyclerView recyclerView = findViewById(R.id.recycler); 50 | recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); 51 | DemoRecyclerViewAdapter recyclerAdapter = new DemoRecyclerViewAdapter(8, screenWidth / 3); 52 | recyclerView.setAdapter(recyclerAdapter); 53 | 54 | recyclerView.setPadding(screenWidth / 3, 0, screenWidth / 3, 0); 55 | 56 | ScrollingPagerIndicator recyclerIndicator = findViewById(R.id.recycler_indicator); 57 | ScrollingPagerIndicator customRecyclerIndicator = findViewById(R.id.custom_recycler_indicator); 58 | // Consider page in the middle current 59 | recyclerIndicator.attachToRecyclerView(recyclerView); 60 | customRecyclerIndicator.attachToRecyclerView(recyclerView); 61 | 62 | SnapHelper snapHelper = new PagerSnapHelper(); 63 | snapHelper.attachToRecyclerView(recyclerView); 64 | 65 | // Some controls 66 | NumberPicker pageCountPicker = findViewById(R.id.page_number_picker); 67 | pageCountPicker.setMaxValue(99); 68 | pageCountPicker.setMinValue(0); 69 | pageCountPicker.setValue(pagerAdapter.getCount()); 70 | 71 | NumberPicker visibleDotCountPicker = findViewById(R.id.visible_dot_number_picker); 72 | visibleDotCountPicker.setMinValue(3); 73 | visibleDotCountPicker.setMaxValue(11); 74 | visibleDotCountPicker.setValue(pagerIndicator.getVisibleDotCount()); 75 | 76 | visibleDotCountPicker.setOnValueChangedListener((picker, oldVal, newVal) -> { 77 | if (newVal % 2 == 0) { 78 | Toast.makeText(this, "Visible dot count must be odd number", Toast.LENGTH_SHORT).show(); 79 | return; 80 | } 81 | pagerIndicator.setVisibleDotCount(newVal); 82 | recyclerIndicator.setVisibleDotCount(newVal); 83 | }); 84 | 85 | pageCountPicker.setOnValueChangedListener((picker, oldVal, newVal) -> { 86 | if (pager.getCurrentItem() >= newVal - 1) { 87 | pager.setCurrentItem(newVal - 1, false); 88 | } 89 | pagerAdapter.setCount(newVal); 90 | recyclerAdapter.setCount(newVal); 91 | }); 92 | } 93 | 94 | private int getScreenWidth() { 95 | Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 96 | Point screenSize = new Point(); 97 | display.getSize(screenSize); 98 | return screenSize.x; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /demo/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /demo/src/main/res/drawable/baseline_accessibility_new_24.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /demo/src/main/res/drawable/baseline_free_breakfast_24.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /demo/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /demo/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 8 | 14 | 15 | 23 | 24 | 36 | 37 | 42 | 43 | 51 | 52 | 62 | 63 | 68 | 69 | 76 | 77 | 84 | 85 | 97 | 98 | 112 | 113 | 123 | 124 | 132 | 133 | 140 | 141 | 151 | 152 | 153 | 154 | -------------------------------------------------------------------------------- /demo/src/main/res/layout/demo_page.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 15 | 16 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinkoff-mobile-tech/ScrollingPagerIndicator/b4b0f2bde72148543692876f0268f5379cc38ed0/demo/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinkoff-mobile-tech/ScrollingPagerIndicator/b4b0f2bde72148543692876f0268f5379cc38ed0/demo/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinkoff-mobile-tech/ScrollingPagerIndicator/b4b0f2bde72148543692876f0268f5379cc38ed0/demo/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinkoff-mobile-tech/ScrollingPagerIndicator/b4b0f2bde72148543692876f0268f5379cc38ed0/demo/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinkoff-mobile-tech/ScrollingPagerIndicator/b4b0f2bde72148543692876f0268f5379cc38ed0/demo/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinkoff-mobile-tech/ScrollingPagerIndicator/b4b0f2bde72148543692876f0268f5379cc38ed0/demo/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinkoff-mobile-tech/ScrollingPagerIndicator/b4b0f2bde72148543692876f0268f5379cc38ed0/demo/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinkoff-mobile-tech/ScrollingPagerIndicator/b4b0f2bde72148543692876f0268f5379cc38ed0/demo/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinkoff-mobile-tech/ScrollingPagerIndicator/b4b0f2bde72148543692876f0268f5379cc38ed0/demo/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinkoff-mobile-tech/ScrollingPagerIndicator/b4b0f2bde72148543692876f0268f5379cc38ed0/demo/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /demo/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | #707dc6 8 | #f43d7b 9 | 10 | -------------------------------------------------------------------------------- /demo/src/main/res/values/dimen.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 100dp 5 | 6 | -------------------------------------------------------------------------------- /demo/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | ScrollingPagerIndicator 3 | 4 | Visible dot count 5 | Page count 6 | 7 | RecyclerView 8 | ViewPager 9 | ViewPager2 10 | 11 | 12 | -------------------------------------------------------------------------------- /demo/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | android.useAndroidX=true 19 | 20 | VERSION_NAME=1.2.5 21 | VERSION_CODE=15 22 | GROUP=ru.tinkoff.scrollingpagerindicator 23 | 24 | POM_DESCRIPTION=Pager indicator inspired by Instagram. Lightweight and easy to set up. 25 | POM_URL=https://github.com/TinkoffCreditSystems/scrollingpagerindicator 26 | POM_SCM_URL=https://github.com/TinkoffCreditSystems/scrollingpagerindicator 27 | POM_SCM_CONNECTION=scm:git@github.com:TinkoffCreditSystems/scrollingpagerindicator.git 28 | POM_SCM_DEV_CONNECTION=scm:git@github.com:TinkoffCreditSystems/scrollingpagerindicator.git 29 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 30 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 31 | POM_LICENCE_DIST=repo 32 | POM_DEVELOPER_ID=tcs 33 | POM_DEVELOPER_NAME=Tinkoff Bank 34 | -------------------------------------------------------------------------------- /gradle/publish-lib.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2016 Tinkoff Bank 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | apply plugin: 'maven-publish' 17 | apply plugin: 'signing' 18 | 19 | def isAndroidLibrary = project.extensions.findByName('android') != null 20 | 21 | def getReleaseRepositoryUrl() { 22 | return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL 23 | : "https://oss.sonatype.org/service/local/staging/deploy/maven2/" 24 | } 25 | 26 | def getSnapshotRepositoryUrl() { 27 | return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL 28 | : "https://oss.sonatype.org/content/repositories/snapshots/" 29 | } 30 | 31 | def getRepositoryUsername() { 32 | return hasProperty('ossrhUsername') ? ossrhUsername : '' 33 | } 34 | 35 | def getRepositoryPassword() { 36 | return hasProperty('ossrhPassword') ? ossrhPassword : '' 37 | } 38 | 39 | afterEvaluate { 40 | publishing { 41 | publications { 42 | release(MavenPublication) { 43 | from isAndroidLibrary ? components.release : components.java 44 | groupId GROUP 45 | version versionName 46 | artifactId POM_ARTIFACT_ID 47 | afterEvaluate { 48 | artifact sourcesJar 49 | artifact javadocJar 50 | } 51 | pom { 52 | name = POM_NAME 53 | packaging = POM_PACKAGING 54 | description = POM_DESCRIPTION 55 | url = POM_URL 56 | scm { 57 | url = POM_SCM_URL 58 | connection = POM_SCM_CONNECTION 59 | developerConnection = POM_SCM_DEV_CONNECTION 60 | } 61 | licenses { 62 | license { 63 | name = POM_LICENCE_NAME 64 | url = POM_LICENCE_URL 65 | distribution = POM_LICENCE_DIST 66 | } 67 | } 68 | developers { 69 | developer { 70 | id = POM_DEVELOPER_ID 71 | name = POM_DEVELOPER_NAME 72 | } 73 | } 74 | } 75 | } 76 | } 77 | repositories { 78 | maven { 79 | url isRelease ? getReleaseRepositoryUrl() : getSnapshotRepositoryUrl() 80 | credentials { 81 | username = getRepositoryUsername() 82 | password = getRepositoryPassword() 83 | } 84 | } 85 | } 86 | } 87 | 88 | tasks.register('sourcesJar', Jar) { 89 | archiveClassifier.set('sources') 90 | from android.sourceSets.main.java.srcDirs 91 | } 92 | 93 | tasks.register('androidJavadocJar', Javadoc) { 94 | dependsOn(preBuild) 95 | if (JavaVersion.current().isJava8Compatible()) { 96 | options.addStringOption('Xdoclint:none', '-quiet') 97 | } 98 | source = android.sourceSets.main.java.source 99 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 100 | classpath += files(android.libraryVariants.collect { variant -> 101 | variant.javaCompile.classpath.files 102 | }) 103 | } 104 | 105 | tasks.register('javadocJar', Jar) { 106 | dependsOn(tasks.named('androidJavadocJar')) 107 | archiveClassifier.set('javadoc') 108 | from "$buildDir/docs/javadoc" 109 | } 110 | 111 | signing { 112 | required { isRelease } 113 | sign publishing.publications.release 114 | } 115 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinkoff-mobile-tech/ScrollingPagerIndicator/b4b0f2bde72148543692876f0268f5379cc38ed0/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 07 17:17:41 MSK 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-7.5-bin.zip -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /readmeAssets/custom-drawables.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinkoff-mobile-tech/ScrollingPagerIndicator/b4b0f2bde72148543692876f0268f5379cc38ed0/readmeAssets/custom-drawables.gif -------------------------------------------------------------------------------- /readmeAssets/demo-horizontal.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinkoff-mobile-tech/ScrollingPagerIndicator/b4b0f2bde72148543692876f0268f5379cc38ed0/readmeAssets/demo-horizontal.gif -------------------------------------------------------------------------------- /readmeAssets/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tinkoff-mobile-tech/ScrollingPagerIndicator/b4b0f2bde72148543692876f0268f5379cc38ed0/readmeAssets/demo.gif -------------------------------------------------------------------------------- /scrollingpagerindicator/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply from: "$project.rootDir/gradle/publish-lib.gradle" 3 | 4 | def customGradleScript = "$project.rootDir/gradle/local.gradle" 5 | if(new File(customGradleScript).exists()){ 6 | apply from: customGradleScript 7 | } 8 | 9 | android { 10 | namespace "ru.tinkoff.scrollingpagerindicator" 11 | 12 | compileSdkVersion rootProject.compileSdk 13 | 14 | defaultConfig { 15 | minSdkVersion rootProject.minSdk 16 | targetSdkVersion rootProject.targetSdk 17 | } 18 | 19 | libraryVariants.all { 20 | it.getGenerateBuildConfigProvider().get().enabled = false 21 | } 22 | } 23 | 24 | tasks.withType(Javadoc) { 25 | options.addStringOption('encoding', 'UTF-8') 26 | options.addStringOption('charSet', 'UTF-8') 27 | } 28 | 29 | dependencies { 30 | compileOnly "androidx.viewpager:viewpager:$rootProject.viewPagerVersion" 31 | compileOnly "androidx.viewpager2:viewpager2:$rootProject.viewPager2Version" 32 | compileOnly "androidx.recyclerview:recyclerview:$rootProject.recyclerViewVersion" 33 | } 34 | -------------------------------------------------------------------------------- /scrollingpagerindicator/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_NAME=ScrollingPagerIndicator 2 | POM_ARTIFACT_ID=scrollingpagerindicator 3 | POM_PACKAGING=aar 4 | -------------------------------------------------------------------------------- /scrollingpagerindicator/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /scrollingpagerindicator/src/main/java/ru/tinkoff/scrollingpagerindicator/AbstractViewPagerAttacher.java: -------------------------------------------------------------------------------- 1 | package ru.tinkoff.scrollingpagerindicator; 2 | 3 | public abstract class AbstractViewPagerAttacher implements ScrollingPagerIndicator.PagerAttacher { 4 | 5 | public void updateIndicatorOnPagerScrolled(ScrollingPagerIndicator indicator, int position, float positionOffset) { 6 | final float offset; 7 | // ViewPager may emit negative positionOffset for very fast scrolling 8 | if (positionOffset < 0) { 9 | offset = 0; 10 | } else if (positionOffset > 1) { 11 | offset = 1; 12 | } else { 13 | offset = positionOffset; 14 | } 15 | indicator.onPageScrolled(position, offset); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /scrollingpagerindicator/src/main/java/ru/tinkoff/scrollingpagerindicator/RecyclerViewAttacher.java: -------------------------------------------------------------------------------- 1 | package ru.tinkoff.scrollingpagerindicator; 2 | 3 | import android.view.View; 4 | 5 | import androidx.annotation.NonNull; 6 | import androidx.annotation.Nullable; 7 | import androidx.recyclerview.widget.LinearLayoutManager; 8 | import androidx.recyclerview.widget.RecyclerView; 9 | 10 | /** 11 | * @author Nikita Olifer 12 | * Attacher for RecyclerView. 13 | */ 14 | public class RecyclerViewAttacher implements ScrollingPagerIndicator.PagerAttacher { 15 | 16 | private ScrollingPagerIndicator indicator; 17 | private RecyclerView recyclerView; 18 | private LinearLayoutManager layoutManager; 19 | private RecyclerView.Adapter attachedAdapter; 20 | 21 | private RecyclerView.OnScrollListener scrollListener; 22 | private RecyclerView.AdapterDataObserver dataObserver; 23 | 24 | private final boolean centered; 25 | private final int currentPageOffset; 26 | 27 | private int measuredChildWidth; 28 | private int measuredChildHeight; 29 | 30 | /** 31 | * Default constructor. Use this if current page in recycler is centered. 32 | * All pages must have the same width. 33 | * Like this: 34 | *

35 | * +------------------------------+ 36 | * |---+ +----------------+ +---| 37 | * | | | current | | | 38 | * | | | page | | | 39 | * |---+ +----------------+ +---| 40 | * +------------------------------+ 41 | */ 42 | public RecyclerViewAttacher() { 43 | currentPageOffset = 0; // Unused when centered 44 | centered = true; 45 | } 46 | 47 | /** 48 | * Use this constructor if current page in recycler isn't centered. 49 | * All pages must have the same width. 50 | * Like this: 51 | *

52 | * +-|----------------------------+ 53 | * | +--------+ +--------+ +----| 54 | * | | current| | | | | 55 | * | | page | | | | | 56 | * | +--------+ +--------+ +----| 57 | * +-|----------------------------+ 58 | * | currentPageOffset 59 | * | 60 | * 61 | * @param currentPageOffset x coordinate of current view left corner/top relative to recycler view. 62 | */ 63 | public RecyclerViewAttacher(int currentPageOffset) { 64 | this.currentPageOffset = currentPageOffset; 65 | this.centered = false; 66 | } 67 | 68 | @Override 69 | public void attachToPager(@NonNull final ScrollingPagerIndicator indicator, @NonNull final RecyclerView pager) { 70 | if (!(pager.getLayoutManager() instanceof LinearLayoutManager)) { 71 | throw new IllegalStateException("Only LinearLayoutManager is supported"); 72 | } 73 | if (pager.getAdapter() == null) { 74 | throw new IllegalStateException("RecyclerView has not Adapter attached"); 75 | } 76 | this.layoutManager = (LinearLayoutManager) pager.getLayoutManager(); 77 | this.recyclerView = pager; 78 | this.attachedAdapter = pager.getAdapter(); 79 | this.indicator = indicator; 80 | 81 | dataObserver = new RecyclerView.AdapterDataObserver() { 82 | @Override 83 | public void onChanged() { 84 | indicator.setDotCount(attachedAdapter.getItemCount()); 85 | updateCurrentOffset(); 86 | } 87 | 88 | @Override 89 | public void onItemRangeChanged(int positionStart, int itemCount) { 90 | onChanged(); 91 | } 92 | 93 | @Override 94 | public void onItemRangeChanged(int positionStart, int itemCount, Object payload) { 95 | onChanged(); 96 | } 97 | 98 | @Override 99 | public void onItemRangeInserted(int positionStart, int itemCount) { 100 | onChanged(); 101 | } 102 | 103 | @Override 104 | public void onItemRangeRemoved(int positionStart, int itemCount) { 105 | onChanged(); 106 | } 107 | 108 | @Override 109 | public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { 110 | onChanged(); 111 | } 112 | }; 113 | attachedAdapter.registerAdapterDataObserver(dataObserver); 114 | indicator.setDotCount(attachedAdapter.getItemCount()); 115 | updateCurrentOffset(); 116 | 117 | scrollListener = new RecyclerView.OnScrollListener() { 118 | @Override 119 | public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { 120 | if (newState == RecyclerView.SCROLL_STATE_IDLE && isInIdleState()) { 121 | int newPosition = findCompletelyVisiblePosition(); 122 | if (newPosition != RecyclerView.NO_POSITION) { 123 | indicator.setDotCount(attachedAdapter.getItemCount()); 124 | if (newPosition < attachedAdapter.getItemCount()) { 125 | indicator.setCurrentPosition(newPosition); 126 | } 127 | } 128 | } 129 | } 130 | 131 | @Override 132 | public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { 133 | updateCurrentOffset(); 134 | } 135 | }; 136 | 137 | recyclerView.addOnScrollListener(scrollListener); 138 | } 139 | 140 | @Override 141 | public void detachFromPager() { 142 | attachedAdapter.unregisterAdapterDataObserver(dataObserver); 143 | recyclerView.removeOnScrollListener(scrollListener); 144 | measuredChildWidth = 0; 145 | } 146 | 147 | private void updateCurrentOffset() { 148 | final View firstView = findFirstVisibleView(); 149 | if (firstView == null) { 150 | return; 151 | } 152 | 153 | int position = recyclerView.getChildAdapterPosition(firstView); 154 | if (position == RecyclerView.NO_POSITION) { 155 | return; 156 | } 157 | final int itemCount = attachedAdapter.getItemCount(); 158 | 159 | // In case there is an infinite pager 160 | if (position >= itemCount && itemCount != 0) { 161 | position = position % itemCount; 162 | } 163 | 164 | float offset; 165 | if (layoutManager.getOrientation() == LinearLayoutManager.HORIZONTAL) { 166 | offset = (getCurrentFrameLeft() - firstView.getX()) / firstView.getMeasuredWidth(); 167 | } else { 168 | offset = (getCurrentFrameBottom() - firstView.getY()) / firstView.getMeasuredHeight(); 169 | } 170 | 171 | if (offset >= 0 && offset <= 1 && position < itemCount) { 172 | indicator.onPageScrolled(position, offset); 173 | } 174 | } 175 | 176 | private int findCompletelyVisiblePosition() { 177 | for (int i = 0; i < recyclerView.getChildCount(); i++) { 178 | View child = recyclerView.getChildAt(i); 179 | 180 | float position = child.getX(); 181 | int size = child.getMeasuredWidth(); 182 | float currentStart = getCurrentFrameLeft(); 183 | float currentEnd = getCurrentFrameRight(); 184 | if (layoutManager.getOrientation() == LinearLayoutManager.VERTICAL) { 185 | position = child.getY(); 186 | size = child.getMeasuredHeight(); 187 | currentStart = getCurrentFrameTop(); 188 | currentEnd = getCurrentFrameBottom(); 189 | } 190 | 191 | if (position >= currentStart && position + size <= currentEnd) { 192 | RecyclerView.ViewHolder holder = recyclerView.findContainingViewHolder(child); 193 | if (holder != null && holder.getAdapterPosition() != RecyclerView.NO_POSITION) { 194 | return holder.getAdapterPosition(); 195 | } 196 | } 197 | } 198 | return RecyclerView.NO_POSITION; 199 | } 200 | 201 | private boolean isInIdleState() { 202 | return findCompletelyVisiblePosition() != RecyclerView.NO_POSITION; 203 | } 204 | 205 | @Nullable 206 | private View findFirstVisibleView() { 207 | int childCount = layoutManager.getChildCount(); 208 | if (childCount == 0) { 209 | return null; 210 | } 211 | 212 | View closestChild = null; 213 | int firstVisibleChild = Integer.MAX_VALUE; 214 | 215 | for (int i = 0; i < childCount; i++) { 216 | final View child = layoutManager.getChildAt(i); 217 | 218 | if (layoutManager.getOrientation() == LinearLayoutManager.HORIZONTAL) { 219 | // Default implementation change: use getX instead of helper 220 | int childStart = (int) child.getX(); 221 | 222 | // if child is more to start than previous closest, set it as closest 223 | 224 | // Default implementation change: 225 | // Fix for any count of visible items 226 | // We make assumption that all children have the same width 227 | if (childStart + child.getMeasuredWidth() < firstVisibleChild 228 | && childStart + child.getMeasuredWidth() >= getCurrentFrameLeft()) { 229 | firstVisibleChild = childStart; 230 | closestChild = child; 231 | } 232 | } else { 233 | // Default implementation change: use geetY instead of helper 234 | int childStart = (int) child.getY(); 235 | 236 | // if child is more to top than previous closest, set it as closest 237 | 238 | // Default implementation change: 239 | // Fix for any count of visible items 240 | // We make assumption that all children have the same height 241 | if (childStart + child.getMeasuredHeight() < firstVisibleChild 242 | && childStart + child.getMeasuredHeight() >= getCurrentFrameBottom()) { 243 | firstVisibleChild = childStart; 244 | closestChild = child; 245 | } 246 | } 247 | } 248 | 249 | return closestChild; 250 | } 251 | 252 | private float getCurrentFrameLeft() { 253 | if (centered) { 254 | return (recyclerView.getMeasuredWidth() - getChildWidth()) / 2; 255 | } else { 256 | return currentPageOffset; 257 | } 258 | } 259 | 260 | private float getCurrentFrameRight() { 261 | if (centered) { 262 | return (recyclerView.getMeasuredWidth() - getChildWidth()) / 2 + getChildWidth(); 263 | } else { 264 | return currentPageOffset + getChildWidth(); 265 | } 266 | } 267 | 268 | private float getCurrentFrameTop() { 269 | if (centered) { 270 | return (recyclerView.getMeasuredHeight() - getChildHeight()) / 2; 271 | } else { 272 | return currentPageOffset; 273 | } 274 | } 275 | 276 | private float getCurrentFrameBottom() { 277 | if (centered) { 278 | return (recyclerView.getMeasuredHeight() - getChildHeight()) / 2 + getChildHeight(); 279 | } else { 280 | return currentPageOffset + getChildHeight(); 281 | } 282 | } 283 | 284 | private float getChildWidth() { 285 | if (measuredChildWidth == 0) { 286 | for (int i = 0; i < recyclerView.getChildCount(); i++) { 287 | View child = recyclerView.getChildAt(i); 288 | if (child.getMeasuredWidth() != 0) { 289 | measuredChildWidth = child.getMeasuredWidth(); 290 | return measuredChildWidth; 291 | } 292 | } 293 | } 294 | return measuredChildWidth; 295 | } 296 | 297 | private float getChildHeight() { 298 | if (measuredChildHeight == 0) { 299 | for (int i = 0; i < recyclerView.getChildCount(); i++) { 300 | View child = recyclerView.getChildAt(i); 301 | if (child.getMeasuredHeight() != 0) { 302 | measuredChildHeight = child.getMeasuredHeight(); 303 | return measuredChildHeight; 304 | } 305 | } 306 | } 307 | return measuredChildHeight; 308 | } 309 | } 310 | -------------------------------------------------------------------------------- /scrollingpagerindicator/src/main/java/ru/tinkoff/scrollingpagerindicator/ScrollingPagerIndicator.java: -------------------------------------------------------------------------------- 1 | package ru.tinkoff.scrollingpagerindicator; 2 | 3 | import android.animation.ArgbEvaluator; 4 | import android.content.Context; 5 | import android.content.res.TypedArray; 6 | import android.graphics.Canvas; 7 | import android.graphics.Paint; 8 | import android.graphics.drawable.Drawable; 9 | import android.os.Build; 10 | import android.util.AttributeSet; 11 | import android.util.SparseArray; 12 | import android.view.View; 13 | import android.widget.LinearLayout; 14 | 15 | import androidx.annotation.ColorInt; 16 | import androidx.annotation.IntDef; 17 | import androidx.annotation.NonNull; 18 | import androidx.annotation.Nullable; 19 | import androidx.recyclerview.widget.LinearLayoutManager; 20 | import androidx.recyclerview.widget.RecyclerView; 21 | import androidx.viewpager.widget.ViewPager; 22 | import androidx.viewpager2.widget.ViewPager2; 23 | 24 | /** 25 | * @author Nikita Olifer 26 | */ 27 | public class ScrollingPagerIndicator extends View { 28 | 29 | @IntDef({RecyclerView.HORIZONTAL, RecyclerView.VERTICAL}) 30 | public @interface Orientation{} 31 | 32 | private int infiniteDotCount; 33 | 34 | private final int dotMinimumSize; 35 | private final int dotNormalSize; 36 | private final int dotSelectedSize; 37 | private final int spaceBetweenDotCenters; 38 | private int visibleDotCount; 39 | private int visibleDotThreshold; 40 | private int orientation; 41 | 42 | private float visibleFramePosition; 43 | private float visibleFrameWidth; 44 | 45 | private float firstDotOffset; 46 | private SparseArray dotScale; 47 | 48 | private int itemCount; 49 | 50 | private final Paint paint; 51 | private final ArgbEvaluator colorEvaluator = new ArgbEvaluator(); 52 | 53 | @ColorInt 54 | private int dotColor; 55 | 56 | @ColorInt 57 | private int selectedDotColor; 58 | 59 | @Nullable 60 | private final Drawable firstDotDrawable; 61 | 62 | @Nullable 63 | private final Drawable lastDotDrawable; 64 | 65 | private boolean looped; 66 | 67 | private Runnable attachRunnable; 68 | private PagerAttacher currentAttacher; 69 | private boolean autoRtl = true; 70 | 71 | private boolean dotCountInitialized; 72 | 73 | public ScrollingPagerIndicator(Context context) { 74 | this(context, null); 75 | } 76 | 77 | public ScrollingPagerIndicator(Context context, @Nullable AttributeSet attrs) { 78 | this(context, attrs, R.attr.scrollingPagerIndicatorStyle); 79 | } 80 | 81 | public ScrollingPagerIndicator(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 82 | super(context, attrs, defStyleAttr); 83 | 84 | TypedArray attributes = context.obtainStyledAttributes( 85 | attrs, R.styleable.ScrollingPagerIndicator, defStyleAttr, R.style.ScrollingPagerIndicator); 86 | dotColor = attributes.getColor(R.styleable.ScrollingPagerIndicator_spi_dotColor, 0); 87 | selectedDotColor = attributes.getColor(R.styleable.ScrollingPagerIndicator_spi_dotSelectedColor, dotColor); 88 | dotNormalSize = attributes.getDimensionPixelSize(R.styleable.ScrollingPagerIndicator_spi_dotSize, 0); 89 | dotSelectedSize = attributes.getDimensionPixelSize(R.styleable.ScrollingPagerIndicator_spi_dotSelectedSize, 0); 90 | int dotMinimumSize = attributes.getDimensionPixelSize(R.styleable.ScrollingPagerIndicator_spi_dotMinimumSize, -1); 91 | this.dotMinimumSize = dotMinimumSize <= dotNormalSize ? dotMinimumSize : -1; 92 | 93 | spaceBetweenDotCenters = attributes.getDimensionPixelSize(R.styleable.ScrollingPagerIndicator_spi_dotSpacing, 0) + dotNormalSize; 94 | looped = attributes.getBoolean(R.styleable.ScrollingPagerIndicator_spi_looped, false); 95 | int visibleDotCount = attributes.getInt(R.styleable.ScrollingPagerIndicator_spi_visibleDotCount, 0); 96 | setVisibleDotCount(visibleDotCount); 97 | visibleDotThreshold = attributes.getInt(R.styleable.ScrollingPagerIndicator_spi_visibleDotThreshold, 2); 98 | orientation = attributes.getInt(R.styleable.ScrollingPagerIndicator_spi_orientation, RecyclerView.HORIZONTAL); 99 | 100 | firstDotDrawable = attributes.getDrawable(R.styleable.ScrollingPagerIndicator_spi_firstDotDrawable); 101 | lastDotDrawable = attributes.getDrawable(R.styleable.ScrollingPagerIndicator_spi_lastDotDrawable); 102 | attributes.recycle(); 103 | 104 | paint = new Paint(); 105 | paint.setAntiAlias(true); 106 | 107 | if (isInEditMode()) { 108 | setDotCount(visibleDotCount); 109 | onPageScrolled(visibleDotCount / 2, 0); 110 | } 111 | } 112 | 113 | /** 114 | * You should make indicator looped in your PagerAttacher implementation if your custom pager is looped too 115 | * If pager has less items than visible_dot_count, indicator will work as usual; 116 | * otherwise it will always be in infinite state. 117 | * 118 | * @param looped true if pager is looped 119 | */ 120 | public void setLooped(boolean looped) { 121 | this.looped = looped; 122 | reattach(); 123 | invalidate(); 124 | } 125 | 126 | /** 127 | * @return not selected dot color 128 | */ 129 | @ColorInt 130 | public int getDotColor() { 131 | return dotColor; 132 | } 133 | 134 | /** 135 | * Sets dot color 136 | * 137 | * @param color dot color 138 | */ 139 | public void setDotColor(@ColorInt int color) { 140 | this.dotColor = color; 141 | invalidate(); 142 | } 143 | 144 | /** 145 | * @return the selected dot color 146 | */ 147 | @ColorInt 148 | public int getSelectedDotColor() { 149 | return selectedDotColor; 150 | } 151 | 152 | /** 153 | * Sets selected dot color 154 | * 155 | * @param color selected dot color 156 | */ 157 | public void setSelectedDotColor(@ColorInt int color) { 158 | this.selectedDotColor = color; 159 | invalidate(); 160 | } 161 | 162 | /** 163 | * Maximum number of dots which will be visible at the same time. 164 | * If pager has more pages than visible_dot_count, indicator will scroll to show extra dots. 165 | * Must be odd number. 166 | * 167 | * @return visible dot count 168 | */ 169 | public int getVisibleDotCount() { 170 | return visibleDotCount; 171 | } 172 | 173 | /** 174 | * Sets visible dot count. Maximum number of dots which will be visible at the same time. 175 | * If pager has more pages than visible_dot_count, indicator will scroll to show extra dots. 176 | * Must be odd number. 177 | * 178 | * @param visibleDotCount visible dot count 179 | * @throws IllegalStateException when pager is already attached 180 | */ 181 | public void setVisibleDotCount(int visibleDotCount) { 182 | if (visibleDotCount % 2 == 0) { 183 | throw new IllegalArgumentException("visibleDotCount must be odd"); 184 | } 185 | this.visibleDotCount = visibleDotCount; 186 | this.infiniteDotCount = visibleDotCount + 2; 187 | 188 | if (attachRunnable != null) { 189 | reattach(); 190 | } else { 191 | requestLayout(); 192 | } 193 | } 194 | 195 | /** 196 | * The minimum number of dots which should be visible. 197 | * If pager has less pages than visibleDotThreshold, no dots will be shown. 198 | * 199 | * @return visible dot threshold. 200 | */ 201 | public int getVisibleDotThreshold() { 202 | return visibleDotThreshold; 203 | } 204 | 205 | /** 206 | * Sets the minimum number of dots which should be visible. 207 | * If pager has less pages than visibleDotThreshold, no dots will be shown. 208 | * 209 | * @param visibleDotThreshold visible dot threshold. 210 | */ 211 | public void setVisibleDotThreshold(int visibleDotThreshold) { 212 | this.visibleDotThreshold = visibleDotThreshold; 213 | if (attachRunnable != null) { 214 | reattach(); 215 | } else { 216 | requestLayout(); 217 | } 218 | } 219 | 220 | /** 221 | * The visible orientation of the dots 222 | * 223 | * @return dot orientation (RecyclerView.HORIZONTAL, RecyclerView.VERTICAL) 224 | */ 225 | @Orientation 226 | public int getOrientation() { 227 | return orientation; 228 | } 229 | 230 | /** 231 | * Set the dot orientation 232 | * 233 | * @param orientation dot orientation (RecyclerView.HORIZONTAL, RecyclerView.VERTICAL) 234 | */ 235 | public void setOrientation(@Orientation int orientation) { 236 | this.orientation = orientation; 237 | if (attachRunnable != null) { 238 | reattach(); 239 | } else { 240 | requestLayout(); 241 | } 242 | } 243 | 244 | /** 245 | * Attaches indicator to ViewPager 246 | * 247 | * @param pager pager to attach 248 | */ 249 | public void attachToPager(@NonNull ViewPager pager) { 250 | attachToPager(pager, new ViewPagerAttacher()); 251 | } 252 | 253 | /** 254 | * Attaches indicator to ViewPager2 255 | * 256 | * @param pager pager to attach 257 | */ 258 | public void attachToPager(@NonNull ViewPager2 pager) { 259 | attachToPager(pager, new ViewPager2Attacher()); 260 | } 261 | 262 | /** 263 | * Attaches indicator to RecyclerView. Use this method if current page of the recycler is centered. 264 | * All pages must have the same width. 265 | * Like this: 266 | *

267 | * +------------------------------+ 268 | * |---+ +----------------+ +---| 269 | * | | | current | | | 270 | * | | | page | | | 271 | * |---+ +----------------+ +---| 272 | * +------------------------------+ 273 | * 274 | * @param recyclerView recycler view to attach 275 | */ 276 | public void attachToRecyclerView(@NonNull RecyclerView recyclerView) { 277 | attachToPager(recyclerView, new RecyclerViewAttacher()); 278 | } 279 | 280 | /** 281 | * Attaches indicator to RecyclerView. Use this method if current page of the recycler isn't centered. 282 | * All pages must have the same width. 283 | * Like this: 284 | *

285 | * +-|----------------------------+ 286 | * | +--------+ +--------+ +----| 287 | * | | current| | | | | 288 | * | | page | | | | | 289 | * | +--------+ +--------+ +----| 290 | * +-|----------------------------+ 291 | * | currentPageOffset 292 | * | 293 | * 294 | * @param recyclerView recycler view to attach 295 | * @param currentPageOffset x coordinate of current view left corner/top relative to recycler view 296 | */ 297 | public void attachToRecyclerView(@NonNull RecyclerView recyclerView, int currentPageOffset) { 298 | attachToPager(recyclerView, new RecyclerViewAttacher(currentPageOffset)); 299 | } 300 | 301 | /** 302 | * Attaches to any custom pager 303 | * 304 | * @param pager pager to attach 305 | * @param attacher helper which should setup this indicator to work with custom pager 306 | */ 307 | public void attachToPager(@NonNull final T pager, @NonNull final PagerAttacher attacher) { 308 | detachFromPager(); 309 | attacher.attachToPager(this, pager); 310 | currentAttacher = attacher; 311 | 312 | attachRunnable = new Runnable() { 313 | @Override 314 | public void run() { 315 | itemCount = -1; 316 | attachToPager(pager, attacher); 317 | } 318 | }; 319 | } 320 | 321 | /** 322 | * Detaches indicator from pager. 323 | */ 324 | public void detachFromPager() { 325 | if (currentAttacher != null) { 326 | currentAttacher.detachFromPager(); 327 | currentAttacher = null; 328 | attachRunnable = null; 329 | autoRtl = true; 330 | } 331 | dotCountInitialized = false; 332 | } 333 | 334 | /** 335 | * Detaches indicator from pager and attaches it again. 336 | * It may be useful for refreshing after adapter count change. 337 | */ 338 | public void reattach() { 339 | if (attachRunnable != null) { 340 | attachRunnable.run(); 341 | invalidate(); 342 | } 343 | } 344 | 345 | /** 346 | * This method must be called from ViewPager.OnPageChangeListener.onPageScrolled or from some 347 | * similar callback if you use custom PagerAttacher. 348 | * 349 | * @param page index of the first page currently being displayed 350 | * Page position+1 will be visible if offset is nonzero 351 | * @param offset Value from [0, 1) indicating the offset from the page at position 352 | */ 353 | public void onPageScrolled(int page, float offset) { 354 | if (offset < 0 || offset > 1) { 355 | throw new IllegalArgumentException("Offset must be [0, 1]"); 356 | } else if (page < 0 || page != 0 && page >= itemCount) { 357 | throw new IndexOutOfBoundsException("page must be [0, adapter.getItemCount())"); 358 | } 359 | 360 | if (!looped || itemCount <= visibleDotCount && itemCount > 1) { 361 | dotScale.clear(); 362 | 363 | if (orientation == LinearLayout.HORIZONTAL) { 364 | scaleDotByOffset(page, offset); 365 | 366 | if (page < itemCount - 1) { 367 | scaleDotByOffset(page + 1, 1 - offset); 368 | } else if (itemCount > 1) { 369 | scaleDotByOffset(0, 1 - offset); 370 | } 371 | } else { // Vertical orientation 372 | scaleDotByOffset(page - 1, offset); 373 | scaleDotByOffset(page, 1 - offset); 374 | } 375 | 376 | invalidate(); 377 | } 378 | if (orientation == LinearLayout.HORIZONTAL) { 379 | adjustFramePosition(offset, page); 380 | } else { 381 | adjustFramePosition(offset, page - 1); 382 | } 383 | invalidate(); 384 | } 385 | 386 | /** 387 | * Sets dot count 388 | * 389 | * @param count new dot count 390 | */ 391 | public void setDotCount(int count) { 392 | initDots(count); 393 | } 394 | 395 | /** 396 | * Sets currently selected position (according to your pager's adapter) 397 | * 398 | * @param position new current position 399 | */ 400 | public void setCurrentPosition(int position) { 401 | if (position != 0 && (position < 0 || position >= itemCount)) { 402 | throw new IndexOutOfBoundsException("Position must be [0, adapter.getItemCount()]"); 403 | } 404 | if (itemCount == 0) { 405 | return; 406 | } 407 | adjustFramePosition(0, position); 408 | updateScaleInIdleState(position); 409 | } 410 | 411 | /** 412 | * Sets Rtl direction availability when the view has Rtl direction. 413 | * autoRtl is on by default. 414 | * 415 | * @param autoRtl false means rtl direction doesn't be apply even if view direction is Rtl. 416 | */ 417 | public void setAutoRtl(boolean autoRtl) { 418 | this.autoRtl = autoRtl; 419 | invalidate(); 420 | } 421 | 422 | @Override 423 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 424 | // Width 425 | int measuredWidth; 426 | // Height 427 | int measuredHeight; 428 | 429 | if (orientation == LinearLayoutManager.HORIZONTAL) { 430 | // We ignore widthMeasureSpec because width is based on visibleDotCount 431 | if (isInEditMode()) { 432 | // Maximum width with all dots visible 433 | measuredWidth = (visibleDotCount - 1) * spaceBetweenDotCenters + dotSelectedSize; 434 | } else { 435 | measuredWidth = itemCount >= visibleDotCount 436 | ? (int) visibleFrameWidth 437 | : (itemCount - 1) * spaceBetweenDotCenters + dotSelectedSize; 438 | } 439 | int heightMode = MeasureSpec.getMode(heightMeasureSpec); 440 | int heightSize = MeasureSpec.getSize(heightMeasureSpec); 441 | 442 | // Height 443 | int desiredHeight = dotSelectedSize; 444 | 445 | switch (heightMode) { 446 | case MeasureSpec.EXACTLY: 447 | measuredHeight = heightSize; 448 | break; 449 | case MeasureSpec.AT_MOST: 450 | measuredHeight = Math.min(desiredHeight, heightSize); 451 | break; 452 | case MeasureSpec.UNSPECIFIED: 453 | default: 454 | measuredHeight = desiredHeight; 455 | } 456 | } else { 457 | if (isInEditMode()) { 458 | measuredHeight = (visibleDotCount - 1) * spaceBetweenDotCenters + dotSelectedSize; 459 | } else { 460 | measuredHeight = itemCount >= visibleDotCount 461 | ? (int) visibleFrameWidth 462 | : (itemCount - 1) * spaceBetweenDotCenters + dotSelectedSize; 463 | } 464 | 465 | int widthMode = MeasureSpec.getMode(widthMeasureSpec); 466 | int widthSize = MeasureSpec.getSize(widthMeasureSpec); 467 | 468 | // Width 469 | int desiredWidth = dotSelectedSize; 470 | 471 | switch (widthMode) { 472 | case MeasureSpec.EXACTLY: 473 | measuredWidth = widthSize; 474 | break; 475 | case MeasureSpec.AT_MOST: 476 | measuredWidth = Math.min(desiredWidth, widthSize); 477 | break; 478 | case MeasureSpec.UNSPECIFIED: 479 | default: 480 | measuredWidth = desiredWidth; 481 | } 482 | } 483 | setMeasuredDimension(measuredWidth, measuredHeight); 484 | } 485 | 486 | @Override 487 | protected void onDraw(Canvas canvas) { 488 | int dotCount = getDotCount(); 489 | if (dotCount < visibleDotThreshold) { 490 | return; 491 | } 492 | 493 | // Some empirical coefficients 494 | float scaleDistance = (spaceBetweenDotCenters + (dotSelectedSize - dotNormalSize) / 2) * 0.7f; 495 | float smallScaleDistance = dotSelectedSize / 2; 496 | float centerScaleDistance = 6f / 7f * spaceBetweenDotCenters; 497 | 498 | int firstVisibleDotPos = (int) (visibleFramePosition - firstDotOffset) / spaceBetweenDotCenters; 499 | int lastVisibleDotPos = firstVisibleDotPos 500 | + (int) (visibleFramePosition + visibleFrameWidth - getDotOffsetAt(firstVisibleDotPos)) 501 | / spaceBetweenDotCenters; 502 | 503 | // If real dots count is less than we can draw inside visible frame, we move lastVisibleDotPos 504 | // to the last item 505 | if (firstVisibleDotPos == 0 && lastVisibleDotPos + 1 > dotCount) { 506 | lastVisibleDotPos = dotCount - 1; 507 | } 508 | 509 | for (int i = firstVisibleDotPos; i <= lastVisibleDotPos; i++) { 510 | float dot = getDotOffsetAt(i); 511 | if (dot >= visibleFramePosition && dot < visibleFramePosition + visibleFrameWidth) { 512 | float diameter; 513 | float scale; 514 | 515 | // Calculate scale according to current page position 516 | if (looped && itemCount > visibleDotCount) { 517 | float frameCenter = visibleFramePosition + visibleFrameWidth / 2; 518 | if (dot >= frameCenter - centerScaleDistance 519 | && dot <= frameCenter) { 520 | scale = (dot - frameCenter + centerScaleDistance) / centerScaleDistance; 521 | } else if (dot > frameCenter 522 | && dot < frameCenter + centerScaleDistance) { 523 | scale = 1 - (dot - frameCenter) / centerScaleDistance; 524 | } else { 525 | scale = 0; 526 | } 527 | } else { 528 | scale = getDotScaleAt(i); 529 | } 530 | diameter = dotNormalSize + (dotSelectedSize - dotNormalSize) * scale; 531 | 532 | // Additional scale for dots at corners 533 | if (itemCount > visibleDotCount) { 534 | float currentScaleDistance; 535 | if (!looped && (i == 0 || i == dotCount - 1)) { 536 | currentScaleDistance = smallScaleDistance; 537 | } else { 538 | currentScaleDistance = scaleDistance; 539 | } 540 | 541 | int size = getWidth(); 542 | if (orientation == LinearLayoutManager.VERTICAL) { 543 | size = getHeight(); 544 | } 545 | if (dot - visibleFramePosition < currentScaleDistance) { 546 | float calculatedDiameter = diameter * (dot - visibleFramePosition) / currentScaleDistance; 547 | if (calculatedDiameter <= dotMinimumSize) { 548 | diameter = dotMinimumSize; 549 | } else if (calculatedDiameter < diameter) { 550 | diameter = calculatedDiameter; 551 | } 552 | } else if (dot - visibleFramePosition > size - currentScaleDistance) { 553 | float calculatedDiameter = diameter * (-dot + visibleFramePosition + size) / currentScaleDistance; 554 | if (calculatedDiameter <= dotMinimumSize) { 555 | diameter = dotMinimumSize; 556 | } else if (calculatedDiameter < diameter) { 557 | diameter = calculatedDiameter; 558 | } 559 | } 560 | } 561 | 562 | paint.setColor(calculateDotColor(scale)); 563 | final Drawable dotDrawable; 564 | if (i == firstVisibleDotPos) { 565 | dotDrawable = firstDotDrawable; 566 | } else if (i == lastVisibleDotPos) { 567 | dotDrawable = lastDotDrawable; 568 | } else { 569 | dotDrawable = null; 570 | } 571 | if (dotDrawable != null) { 572 | if (orientation == LinearLayoutManager.HORIZONTAL) { 573 | dotDrawable.setBounds((int) (dot - visibleFramePosition - dotSelectedSize / 2), 574 | getMeasuredHeight() / 2 - dotSelectedSize / 2, 575 | (int) (dot - visibleFramePosition + dotSelectedSize / 2), 576 | getMeasuredHeight() / 2 + dotSelectedSize / 2); 577 | } else { 578 | dotDrawable.setBounds(getMeasuredWidth() / 2 - dotSelectedSize / 2, 579 | (int) (dot - visibleFramePosition - dotSelectedSize / 2), 580 | getMeasuredWidth() / 2 + dotSelectedSize / 2, 581 | (int) (dot - visibleFramePosition + dotSelectedSize / 2)); 582 | } 583 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 584 | dotDrawable.setTint(paint.getColor()); 585 | } 586 | dotDrawable.draw(canvas); 587 | } else if (orientation == LinearLayoutManager.HORIZONTAL) { 588 | float cx = dot - visibleFramePosition; 589 | if (autoRtl && isRtl()) { 590 | cx = getWidth() - cx; 591 | } 592 | 593 | canvas.drawCircle(cx, 594 | getMeasuredHeight() / 2, 595 | diameter / 2, 596 | paint); 597 | } else { 598 | canvas.drawCircle(getMeasuredWidth() / 2, 599 | dot - visibleFramePosition, 600 | diameter / 2, 601 | paint); 602 | } 603 | } 604 | } 605 | } 606 | 607 | private boolean isRtl() { 608 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && 609 | getLayoutDirection() == LAYOUT_DIRECTION_RTL; 610 | } 611 | 612 | @ColorInt 613 | private int calculateDotColor(float dotScale) { 614 | return (Integer) colorEvaluator.evaluate(dotScale, dotColor, selectedDotColor); 615 | } 616 | 617 | private void updateScaleInIdleState(int currentPos) { 618 | if (!looped || itemCount < visibleDotCount) { 619 | dotScale.clear(); 620 | dotScale.put(currentPos, 1f); 621 | invalidate(); 622 | } 623 | } 624 | 625 | private void initDots(int itemCount) { 626 | if (this.itemCount == itemCount && dotCountInitialized) { 627 | return; 628 | } 629 | this.itemCount = itemCount; 630 | dotCountInitialized = true; 631 | dotScale = new SparseArray<>(); 632 | 633 | if (itemCount < visibleDotThreshold) { 634 | requestLayout(); 635 | invalidate(); 636 | return; 637 | } 638 | 639 | firstDotOffset = looped && this.itemCount > visibleDotCount ? 0 : dotSelectedSize / 2; 640 | visibleFrameWidth = (visibleDotCount - 1) * spaceBetweenDotCenters + dotSelectedSize; 641 | 642 | requestLayout(); 643 | invalidate(); 644 | } 645 | 646 | private int getDotCount() { 647 | if (looped && itemCount > visibleDotCount) { 648 | return infiniteDotCount; 649 | } else { 650 | return itemCount; 651 | } 652 | } 653 | 654 | private void adjustFramePosition(float offset, int pos) { 655 | if (itemCount <= visibleDotCount) { 656 | // Without scroll 657 | visibleFramePosition = 0; 658 | } else if (!looped && itemCount > visibleDotCount) { 659 | // Not looped with scroll 660 | float center = getDotOffsetAt(pos) + spaceBetweenDotCenters * offset; 661 | visibleFramePosition = center - visibleFrameWidth / 2; 662 | 663 | // Block frame offset near start and end 664 | int firstCenteredDotIndex = visibleDotCount / 2; 665 | float lastCenteredDot = getDotOffsetAt(getDotCount() - 1 - firstCenteredDotIndex); 666 | if (visibleFramePosition + visibleFrameWidth / 2 < getDotOffsetAt(firstCenteredDotIndex)) { 667 | visibleFramePosition = getDotOffsetAt(firstCenteredDotIndex) - visibleFrameWidth / 2; 668 | } else if (visibleFramePosition + visibleFrameWidth / 2 > lastCenteredDot) { 669 | visibleFramePosition = lastCenteredDot - visibleFrameWidth / 2; 670 | } 671 | } else { 672 | // Looped with scroll 673 | float center = getDotOffsetAt(infiniteDotCount / 2) + spaceBetweenDotCenters * offset; 674 | visibleFramePosition = center - visibleFrameWidth / 2; 675 | } 676 | } 677 | 678 | private void scaleDotByOffset(int position, float offset) { 679 | if (dotScale == null || getDotCount() == 0) { 680 | return; 681 | } 682 | setDotScaleAt(position, 1 - Math.abs(offset)); 683 | } 684 | 685 | private float getDotOffsetAt(int index) { 686 | return firstDotOffset + index * spaceBetweenDotCenters; 687 | } 688 | 689 | private float getDotScaleAt(int index) { 690 | Float scale = dotScale.get(index); 691 | if (scale != null) { 692 | return scale; 693 | } 694 | return 0; 695 | } 696 | 697 | private void setDotScaleAt(int index, float scale) { 698 | if (scale == 0) { 699 | dotScale.remove(index); 700 | } else { 701 | dotScale.put(index, scale); 702 | } 703 | } 704 | 705 | /** 706 | * Interface for attaching to custom pagers. 707 | * 708 | * @param custom pager's class 709 | */ 710 | public interface PagerAttacher { 711 | 712 | /** 713 | * Here you should add all needed callbacks to track pager's item count, position and offset 714 | * You must call: 715 | * {@link ScrollingPagerIndicator#setDotCount(int)} - initially and after page selection, 716 | * {@link ScrollingPagerIndicator#setCurrentPosition(int)} - initially and after page selection, 717 | * {@link ScrollingPagerIndicator#onPageScrolled(int, float)} - in your pager callback to track scroll offset, 718 | * {@link ScrollingPagerIndicator#reattach()} - each time your adapter items change. 719 | * 720 | * @param indicator indicator 721 | * @param pager pager to attach 722 | */ 723 | void attachToPager(@NonNull ScrollingPagerIndicator indicator, @NonNull T pager); 724 | 725 | /** 726 | * Here you should unregister all callbacks previously added to pager and adapter 727 | */ 728 | void detachFromPager(); 729 | } 730 | } 731 | -------------------------------------------------------------------------------- /scrollingpagerindicator/src/main/java/ru/tinkoff/scrollingpagerindicator/ViewPager2Attacher.java: -------------------------------------------------------------------------------- 1 | package ru.tinkoff.scrollingpagerindicator; 2 | 3 | import androidx.annotation.NonNull; 4 | import androidx.recyclerview.widget.RecyclerView; 5 | import androidx.viewpager2.widget.ViewPager2; 6 | 7 | public class ViewPager2Attacher extends AbstractViewPagerAttacher { 8 | 9 | private RecyclerView.AdapterDataObserver dataSetObserver; 10 | private RecyclerView.Adapter attachedAdapter; 11 | private ViewPager2.OnPageChangeCallback onPageChangeListener; 12 | private ViewPager2 pager; 13 | 14 | @Override 15 | public void attachToPager(@NonNull final ScrollingPagerIndicator indicator, @NonNull final ViewPager2 pager) { 16 | attachedAdapter = pager.getAdapter(); 17 | if (attachedAdapter == null) { 18 | throw new IllegalStateException("Set adapter before call attachToPager() method"); 19 | } 20 | 21 | this.pager = pager; 22 | 23 | updateIndicatorDotsAndPosition(indicator); 24 | 25 | dataSetObserver = new RecyclerView.AdapterDataObserver() { 26 | @Override 27 | public void onChanged() { 28 | indicator.reattach(); 29 | } 30 | }; 31 | attachedAdapter.registerAdapterDataObserver(dataSetObserver); 32 | 33 | onPageChangeListener = new ViewPager2.OnPageChangeCallback() { 34 | 35 | boolean idleState = true; 36 | 37 | @Override 38 | public void onPageScrolled(int position, float positionOffset, int positionOffsetPixel) { 39 | updateIndicatorOnPagerScrolled(indicator, position, positionOffset); 40 | } 41 | 42 | @Override 43 | public void onPageSelected(int position) { 44 | if (idleState) { 45 | updateIndicatorDotsAndPosition(indicator); 46 | } 47 | } 48 | 49 | @Override 50 | public void onPageScrollStateChanged(int state) { 51 | idleState = state == ViewPager2.SCROLL_STATE_IDLE; 52 | } 53 | }; 54 | 55 | pager.registerOnPageChangeCallback(onPageChangeListener); 56 | } 57 | 58 | @Override 59 | public void detachFromPager() { 60 | attachedAdapter.unregisterAdapterDataObserver(dataSetObserver); 61 | pager.unregisterOnPageChangeCallback(onPageChangeListener); 62 | } 63 | 64 | private void updateIndicatorDotsAndPosition(ScrollingPagerIndicator indicator) { 65 | indicator.setDotCount(attachedAdapter.getItemCount()); 66 | indicator.setCurrentPosition(pager.getCurrentItem()); 67 | } 68 | } -------------------------------------------------------------------------------- /scrollingpagerindicator/src/main/java/ru/tinkoff/scrollingpagerindicator/ViewPagerAttacher.java: -------------------------------------------------------------------------------- 1 | package ru.tinkoff.scrollingpagerindicator; 2 | 3 | import android.database.DataSetObserver; 4 | import androidx.annotation.NonNull; 5 | import androidx.viewpager.widget.PagerAdapter; 6 | import androidx.viewpager.widget.ViewPager; 7 | 8 | /** 9 | * @author Nikita Olifer 10 | */ 11 | public class ViewPagerAttacher extends AbstractViewPagerAttacher { 12 | 13 | private DataSetObserver dataSetObserver; 14 | private ViewPager.OnPageChangeListener onPageChangeListener; 15 | private ViewPager pager; 16 | private PagerAdapter attachedAdapter; 17 | 18 | @Override 19 | public void attachToPager(@NonNull final ScrollingPagerIndicator indicator, @NonNull final ViewPager pager) { 20 | attachedAdapter = pager.getAdapter(); 21 | if (attachedAdapter == null) { 22 | throw new IllegalStateException("Set adapter before call attachToPager() method"); 23 | } 24 | 25 | this.pager = pager; 26 | 27 | updateIndicatorDotsAndPosition(indicator); 28 | 29 | dataSetObserver = new DataSetObserver() { 30 | @Override 31 | public void onChanged() { 32 | indicator.reattach(); 33 | } 34 | 35 | @Override 36 | public void onInvalidated() { 37 | onChanged(); 38 | } 39 | }; 40 | attachedAdapter.registerDataSetObserver(dataSetObserver); 41 | 42 | onPageChangeListener = new ViewPager.OnPageChangeListener() { 43 | 44 | boolean idleState = true; 45 | 46 | @Override 47 | public void onPageScrolled(int position, float positionOffset, int positionOffsetPixel) { 48 | updateIndicatorOnPagerScrolled(indicator, position, positionOffset); 49 | } 50 | 51 | @Override 52 | public void onPageSelected(int position) { 53 | if (idleState) { 54 | updateIndicatorDotsAndPosition(indicator); 55 | } 56 | } 57 | 58 | @Override 59 | public void onPageScrollStateChanged(int state) { 60 | idleState = state == ViewPager.SCROLL_STATE_IDLE; 61 | } 62 | }; 63 | pager.addOnPageChangeListener(onPageChangeListener); 64 | } 65 | 66 | @Override 67 | public void detachFromPager() { 68 | attachedAdapter.unregisterDataSetObserver(dataSetObserver); 69 | pager.removeOnPageChangeListener(onPageChangeListener); 70 | } 71 | 72 | private void updateIndicatorDotsAndPosition(ScrollingPagerIndicator indicator) { 73 | indicator.setDotCount(attachedAdapter.getCount()); 74 | indicator.setCurrentPosition(pager.getCurrentItem()); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /scrollingpagerindicator/src/main/res/values/attrs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /scrollingpagerindicator/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 13 | 14 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':demo', ':scrollingpagerindicator' 2 | 3 | --------------------------------------------------------------------------------