├── .gitignore ├── LICENSE ├── README.md ├── README_cn.md ├── app ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── infinitebanner │ │ ├── BannerAdapter.java │ │ └── MainActivity.java │ └── res │ ├── drawable-xxhdpi │ ├── img_0.jpg │ ├── img_1.jpg │ └── img_2.jpg │ ├── layout │ └── activity_main.xml │ └── values │ ├── colors.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── gif └── demo.gif ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── library ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── github │ │ └── infinitebanner │ │ ├── AbsBannerAdapter.java │ │ └── InfiniteBannerView.java │ └── res │ └── values │ ├── attrs.xml │ └── strings.xml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | *.apk 3 | *.ap_ 4 | *.dex 5 | *.class 6 | *.log 7 | .gradle 8 | /bin 9 | /gen 10 | /local.properties 11 | /.idea 12 | /build 13 | .DS_Store 14 | /captures 15 | /app/build 16 | /library/build -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | English | [中文文档](README_cn.md) 2 | 3 | # InfiniteBanner 4 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 5 | [![Platform](https://img.shields.io/badge/platform-android-green.svg)](http://developer.android.com/index.html) 6 | [![API](https://img.shields.io/badge/API-14%2B-brightgreen.svg?style=flat)](https://android-arsenal.com/api?level=14) 7 | [![](https://jitpack.io/v/Marksss/InfiniteBanner.svg)](https://jitpack.io/#Marksss/InfiniteBanner) 8 | 9 | InfiniteBanner is a view that can automatically or manually scroll in a loop for a banner infinitely, which is very easy to use and is similar to ViewPager. Meanwhile, it not only solves the problem that ViewPager cannot scroll infinitely, but also reuses its child views so that less memory will be token while scrolling. 10 | 11 | ![demo-gif](https://github.com/Marksss/InfiniteBanner/blob/master/gif/demo.gif) 12 | ## Usage 13 | ### Add the dependency to your project `build.gradle` file 14 | ``` implementation 'com.github.Marksss:InfiniteBanner:v1.2' ``` 15 | ### Code in XML 16 | ``` 17 | 21 | ``` 22 | If you want it to scroll automatically, just set bannerAutoScroll true. Some other attributes that may be used: 23 | - bannerDividerWidth:distance between child views; 24 | - bannerInitialPage:the initial position after refreshing; 25 | - bannerForegroundWidthPercent:the width of child view that in the middle of container / the container's width(The default value is 1, which means that only one child view can be seen when scolling stops); 26 | - bannerLoopInterval:time interval(millisecond); 27 | - bannerManuallyScrollLock:if manual scrolling is allowed; 28 | - bannerScrollReverse:reverse scrolling automatically. 29 | 30 | ### Code in Java 31 | 32 | Create your own BannerAdapter: 33 | ``` 34 | public class MyBannerAdapter extends AbsBannerAdapter { 35 | @Override 36 | public int getCount() { 37 | //total count 38 | ... 39 | } 40 | 41 | @Override 42 | protected View makeView(InfiniteBannerView parent) { 43 | // create child view if needed 44 | ... 45 | } 46 | 47 | @Override 48 | protected void bind(View view, int position) { 49 | // bind view and data together and show whatever needed 50 | ... 51 | } 52 | } 53 | ``` 54 | ``` 55 | infiniteBannerView.setAdapter(new MyBannerAdapter()); 56 | ``` 57 | When you need to refresh your data: 58 | 59 | ``` 60 | myBannerAdapter.notifyDataSetChanged() 61 | ``` 62 | 63 | ### Click listener 64 | ``` 65 | infiniteBannerView.setOnItemClickListener(new InfiniteBannerView.OnItemClickListener() { 66 | @Override 67 | public void click(InfiniteBannerView view, int position) { 68 | ... 69 | } 70 | }); 71 | ``` 72 | 73 | ### Animation 74 | Similar to ViewPager,you just need to add transformer: 75 | ``` 76 | infiniteBannerView.setPageTransformer(new InfiniteBannerView.PageTransformer() { 77 | @Override 78 | public void transformPage(@NonNull View view, float offset) { 79 | ... 80 | } 81 | }); 82 | ``` 83 | 84 | ### Indicator 85 | There is no any indicators in this library. If you need one, you can add whatever indicator you want as follows(indicator in demo is another open source library [PageIndicatorView](https://github.com/romandanylyk/PageIndicatorView "PageIndicatorView")): 86 | ``` 87 | infiniteBannerView_1.addOnPageChangeListener(new InfiniteBannerView.OnPageChangeListener() { 88 | @Override 89 | public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 90 | ... 91 | } 92 | 93 | @Override 94 | public void onPageSelected(int position) { 95 | ... 96 | } 97 | }); 98 | ``` 99 | ## License 100 | InfiniteBanner is released under the [Apache License Version 2.0](LICENSE). 101 | -------------------------------------------------------------------------------- /README_cn.md: -------------------------------------------------------------------------------- 1 | [English](README.md) | 中文文档 2 | 3 | # InfiniteBanner 4 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 5 | [![Platform](https://img.shields.io/badge/platform-android-green.svg)](http://developer.android.com/index.html) 6 | [![API](https://img.shields.io/badge/API-14%2B-brightgreen.svg?style=flat)](https://android-arsenal.com/api?level=14) 7 | [![](https://jitpack.io/v/Marksss/InfiniteBanner.svg)](https://jitpack.io/#Marksss/InfiniteBanner) 8 | 9 | InfiniteBanner是一个能够无限轮播的banner,它的用法简单而且与ViewPager非常类似,但它也解决了ViewPager无法无限轮播的痛点。同时,它的内部是以子控件复用的形式实现,在无限轮播的同时并不会消耗过多的内存。 10 | 11 | ![demo-gif](https://github.com/Marksss/InfiniteBanner/blob/master/gif/demo.gif) 12 | ## 用法 13 | ### 将以下依赖添加到 `build.gradle` 文件中 14 | ``` implementation 'com.github.Marksss:InfiniteBanner:v1.2' ``` 15 | ### XML中的代码 16 | ``` 17 | 21 | ``` 22 | 如果想让banner自动开启轮播,只需将bannerAutoScroll设置为true即可。其他可能会用到的属性值如下: 23 | - bannerDividerWidth:每个子View之间的间隔距离; 24 | - bannerInitialPage:每次刷新后的起始位置; 25 | - bannerForegroundWidthPercent:居中显示的子View的宽度占容器总宽度的比值(默认是1,即静止的时候只能看到一个子View); 26 | - bannerLoopInterval:自动轮播的时间间隔(微秒); 27 | - bannerManuallyScrollLock:是否静止手划操作; 28 | - bannerScrollReverse:是否反向轮播。 29 | 30 | ### Java中的代码 31 | 实现自己的BannerAdapter: 32 | ``` 33 | public class MyBannerAdapter extends AbsBannerAdapter { 34 | @Override 35 | public int getCount() { 36 | //总数 37 | ... 38 | } 39 | 40 | @Override 41 | protected View makeView(InfiniteBannerView parent) { 42 | // 创建子view 43 | ... 44 | } 45 | 46 | @Override 47 | protected void bind(View view, int position) { 48 | // 子view与数据绑定并展示相应内容 49 | ... 50 | } 51 | } 52 | ``` 53 | ``` 54 | infiniteBannerView.setAdapter(new MyBannerAdapter()); 55 | ``` 56 | 当需要刷新数据时: 57 | 58 | ``` 59 | myBannerAdapter.notifyDataSetChanged() 60 | ``` 61 | 62 | ### 点击事件 63 | ``` 64 | infiniteBannerView.setOnItemClickListener(new InfiniteBannerView.OnItemClickListener() { 65 | @Override 66 | public void click(InfiniteBannerView view, int position) { 67 | ... 68 | } 69 | }); 70 | ``` 71 | 72 | ### 动画效果 73 | 和ViewPager类似,只要添加transformer即可: 74 | ``` 75 | infiniteBannerView.setPageTransformer(new InfiniteBannerView.PageTransformer() { 76 | @Override 77 | public void transformPage(@NonNull View view, float offset) { 78 | ... 79 | } 80 | }); 81 | ``` 82 | 83 | ### 指示器 84 | 本库中并没有添加任何indicator,如果想加indicator,可以用如下类似ViewPager的方式很轻松地添加自己喜欢的indicator(Demo中的indicator是一个开源库[PageIndicatorView](https://github.com/romandanylyk/PageIndicatorView "PageIndicatorView")): 85 | ``` 86 | infiniteBannerView_1.addOnPageChangeListener(new InfiniteBannerView.OnPageChangeListener() { 87 | @Override 88 | public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 89 | ... 90 | } 91 | 92 | @Override 93 | public void onPageSelected(int position) { 94 | ... 95 | } 96 | }); 97 | ``` 98 | 99 | ## 许可证 100 | InfiniteBanner基于 [Apache License Version 2.0](LICENSE) 发布。 -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 30 5 | defaultConfig { 6 | applicationId "com.infinitebanner" 7 | minSdkVersion 15 8 | targetSdkVersion 30 9 | versionCode 11 10 | versionName "1.1" 11 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | } 20 | 21 | dependencies { 22 | implementation fileTree(dir: 'libs', include: ['*.jar']) 23 | implementation 'androidx.appcompat:appcompat:1.0.0' 24 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 25 | implementation 'com.romandanylyk:pageindicatorview:1.0.3' 26 | implementation 'com.github.Marksss:InfiniteBanner:v1.2' 27 | // implementation project(':library') 28 | } 29 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /app/src/main/java/com/infinitebanner/BannerAdapter.java: -------------------------------------------------------------------------------- 1 | package com.infinitebanner; 2 | 3 | import android.content.Context; 4 | import android.view.View; 5 | import android.view.ViewGroup; 6 | import android.widget.ImageView; 7 | 8 | import com.github.infinitebanner.AbsBannerAdapter; 9 | import com.github.infinitebanner.InfiniteBannerView; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | public class BannerAdapter extends AbsBannerAdapter { 15 | 16 | @Override 17 | public int getCount() { 18 | return 3; 19 | } 20 | 21 | @Override 22 | protected View makeView(InfiniteBannerView parent) { 23 | ImageView imageView = new ImageView(parent.getContext()); 24 | imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); 25 | imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 26 | return imageView; 27 | } 28 | 29 | @Override 30 | protected void bind(View view, int position) { 31 | if (position == 0) { 32 | ((ImageView) view).setImageResource(R.drawable.img_0); 33 | } else if (position == 1) { 34 | ((ImageView) view).setImageResource(R.drawable.img_1); 35 | } else { 36 | ((ImageView) view).setImageResource(R.drawable.img_2); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /app/src/main/java/com/infinitebanner/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.infinitebanner; 2 | 3 | import androidx.annotation.NonNull; 4 | import androidx.appcompat.app.AppCompatActivity; 5 | import android.os.Bundle; 6 | import android.view.View; 7 | import android.widget.Toast; 8 | 9 | import com.github.infinitebanner.InfiniteBannerView; 10 | import com.rd.PageIndicatorView; 11 | 12 | public class MainActivity extends AppCompatActivity { 13 | 14 | @Override 15 | protected void onCreate(Bundle savedInstanceState) { 16 | super.onCreate(savedInstanceState); 17 | setContentView(R.layout.activity_main); 18 | 19 | InfiniteBannerView infiniteBannerView_0 = findViewById(R.id.infinite_banner_0); 20 | infiniteBannerView_0.setAdapter(new BannerAdapter()); 21 | infiniteBannerView_0.setPageTransformer(new InfiniteBannerView.PageTransformer() { 22 | @Override 23 | public void transformPage(@NonNull View view, float offset) { 24 | view.setScaleY(0.8f + 0.2f * offset); 25 | view.setAlpha(0.5f + 0.5f * offset); 26 | } 27 | }); 28 | infiniteBannerView_0.setOnItemClickListener(new InfiniteBannerView.OnItemClickListener() { 29 | @Override 30 | public void click(InfiniteBannerView view, int position) { 31 | Toast.makeText(MainActivity.this, ""+position, Toast.LENGTH_SHORT).show(); 32 | } 33 | }); 34 | infiniteBannerView_0.setInitPosition(1); 35 | 36 | InfiniteBannerView infiniteBannerView_1 = findViewById(R.id.infinite_banner_1); 37 | infiniteBannerView_1.setAdapter(new BannerAdapter()); 38 | final PageIndicatorView pageIndicatorView = findViewById(R.id.pageIndicatorView); 39 | pageIndicatorView.setCount(3); 40 | infiniteBannerView_1.addOnPageChangeListener(new InfiniteBannerView.OnPageChangeListener() { 41 | @Override 42 | public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 43 | 44 | } 45 | 46 | @Override 47 | public void onPageSelected(int position) { 48 | pageIndicatorView.setSelection(position); 49 | } 50 | }); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/img_0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marksss/InfiniteBanner/e6e972a63aff21de236e67cbe3c4c3b8fc2ca0ca/app/src/main/res/drawable-xxhdpi/img_0.jpg -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/img_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marksss/InfiniteBanner/e6e972a63aff21de236e67cbe3c4c3b8fc2ca0ca/app/src/main/res/drawable-xxhdpi/img_1.jpg -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/img_2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marksss/InfiniteBanner/e6e972a63aff21de236e67cbe3c4c3b8fc2ca0ca/app/src/main/res/drawable-xxhdpi/img_2.jpg -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 19 | 20 | 34 | 35 | 47 | 48 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #008577 4 | #00574B 5 | #D81B60 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | InfiniteBanner 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | google() 6 | jcenter() 7 | 8 | } 9 | dependencies { 10 | classpath 'com.android.tools.build:gradle:4.2.2' 11 | } 12 | } 13 | 14 | allprojects { 15 | repositories { 16 | mavenCentral() 17 | google() 18 | jcenter() 19 | maven { 20 | url "https://maven.aliyun.com/nexus/content/groups/public/" 21 | } 22 | maven { url 'https://jitpack.io' } 23 | } 24 | } 25 | 26 | task clean(type: Delete) { 27 | delete rootProject.buildDir 28 | } 29 | -------------------------------------------------------------------------------- /gif/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marksss/InfiniteBanner/e6e972a63aff21de236e67cbe3c4c3b8fc2ca0ca/gif/demo.gif -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | android.enableJetifier=true 10 | android.useAndroidX=true 11 | org.gradle.jvmargs=-Xmx1536m 12 | # When configured, Gradle will run in incubating parallel mode. 13 | # This option should only be used with decoupled projects. More details, visit 14 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 15 | # org.gradle.parallel=true 16 | 17 | #systemProp.https.proxyHost=127.0.0.1 18 | #systemProp.https.proxyPort=1092 19 | #systemProp.http.proxyHost=127.0.0.1 20 | #systemProp.http.proxyPort=1092 21 | 22 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marksss/InfiniteBanner/e6e972a63aff21de236e67cbe3c4c3b8fc2ca0ca/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MSYS* | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /library/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 30 5 | 6 | 7 | defaultConfig { 8 | minSdkVersion 15 9 | targetSdkVersion 30 10 | versionCode 12 11 | versionName "1.2" 12 | 13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 14 | 15 | } 16 | 17 | buildTypes { 18 | release { 19 | minifyEnabled false 20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 21 | } 22 | } 23 | 24 | } 25 | 26 | dependencies { 27 | implementation fileTree(dir: 'libs', include: ['*.jar']) 28 | 29 | testImplementation 'junit:junit:4.12' 30 | } 31 | -------------------------------------------------------------------------------- /library/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /library/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/infinitebanner/AbsBannerAdapter.java: -------------------------------------------------------------------------------- 1 | package com.github.infinitebanner; 2 | 3 | import android.content.Context; 4 | import android.database.DataSetObservable; 5 | import android.database.DataSetObserver; 6 | import android.view.View; 7 | 8 | /** 9 | * Created by Marksss on 2019/8/13. 10 | */ 11 | public abstract class AbsBannerAdapter { 12 | private final DataSetObservable mDataSetObservable = new DataSetObservable(); 13 | 14 | void registerDataSetObserver(DataSetObserver observer) { 15 | mDataSetObservable.registerObserver(observer); 16 | } 17 | 18 | void unregisterDataSetObserver(DataSetObserver observer) { 19 | mDataSetObservable.unregisterObserver(observer); 20 | } 21 | 22 | public void notifyDataSetChanged() { 23 | mDataSetObservable.notifyChanged(); 24 | } 25 | 26 | public void notifyDataSetInvalidated() { 27 | mDataSetObservable.notifyInvalidated(); 28 | } 29 | 30 | protected abstract int getCount(); 31 | 32 | protected abstract View makeView(InfiniteBannerView parent); 33 | 34 | protected abstract void bind(View view, int position); 35 | } 36 | -------------------------------------------------------------------------------- /library/src/main/java/com/github/infinitebanner/InfiniteBannerView.java: -------------------------------------------------------------------------------- 1 | package com.github.infinitebanner; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.content.Context; 5 | import android.content.res.TypedArray; 6 | import android.database.DataSetObserver; 7 | import android.os.Handler; 8 | import android.os.Looper; 9 | import android.util.AttributeSet; 10 | import android.util.Log; 11 | import android.util.SparseArray; 12 | import android.view.MotionEvent; 13 | import android.view.VelocityTracker; 14 | import android.view.View; 15 | import android.view.ViewConfiguration; 16 | import android.view.ViewGroup; 17 | import android.widget.Scroller; 18 | 19 | import java.util.ArrayList; 20 | import java.util.List; 21 | 22 | /** 23 | * A banner view that can automatically or manually scroll in a loop 24 | * Created by Marksss on 2019/8/12. 25 | */ 26 | public class InfiniteBannerView extends ViewGroup { 27 | private static final int MAX_SCROLL_X = Integer.MAX_VALUE - (Integer.MAX_VALUE >> 3); 28 | private final Pager mPager = new Pager(); 29 | private long mLoopInterval = 3000; 30 | private AbsBannerAdapter mAdapter; 31 | private final Handler mHandler = new Handler(Looper.getMainLooper()); 32 | private int mDividerWidth = 0; 33 | private float mForegroundWidthPercent = 1f; // 0.34<=percent<=0.1 34 | private boolean mIsReverse, mIsManuallyScrollLocked, mIsAutoScroll; 35 | private boolean mIsTouching, mIsAttachToWindow; 36 | private long mLastTouchTime, mLastScrollTime; 37 | private int mLastX, mLastDownX, mLastDownY; 38 | private Scroller mScroller; 39 | private int mTouchSlop, mMaxVelocity; 40 | private OnItemClickListener mOnItemClickListener; 41 | private List mOnPageChangeListeners = new ArrayList<>(); 42 | private ScrollIntercepter mScrollIntercepter; 43 | private PageTransformer mPageTransformer; 44 | private SparseArray mViewsMap = new SparseArray<>(); 45 | 46 | public InfiniteBannerView(Context context) { 47 | super(context); 48 | init(context, null); 49 | } 50 | 51 | public InfiniteBannerView(Context context, AttributeSet attrs) { 52 | super(context, attrs); 53 | init(context, attrs); 54 | } 55 | 56 | public InfiniteBannerView(Context context, AttributeSet attrs, int defStyleAttr) { 57 | super(context, attrs, defStyleAttr); 58 | init(context, attrs); 59 | } 60 | 61 | private void init(Context context, AttributeSet attrs) { 62 | if (attrs != null) { 63 | TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.InfiniteBannerView); 64 | mDividerWidth = a.getDimensionPixelSize(R.styleable.InfiniteBannerView_bannerDividerWidth, mDividerWidth); 65 | mPager.initPosition(a.getInt(R.styleable.InfiniteBannerView_bannerInitialPage, 0)); 66 | mIsManuallyScrollLocked = a.getBoolean(R.styleable.InfiniteBannerView_bannerManuallyScrollLock, false); 67 | mIsAutoScroll = a.getBoolean(R.styleable.InfiniteBannerView_bannerAutoScroll, false); 68 | mIsReverse = a.getBoolean(R.styleable.InfiniteBannerView_bannerScrollReverse, false); 69 | float foregroundWidthPercent = a.getFloat(R.styleable.InfiniteBannerView_bannerForegroundWidthPercent, mForegroundWidthPercent); 70 | if (foregroundWidthPercent < 1f){ 71 | setForegroundWidthPercent(foregroundWidthPercent); 72 | } 73 | String s = a.getString(R.styleable.InfiniteBannerView_bannerLoopInterval); 74 | if (s != null) { 75 | try { 76 | mLoopInterval = Long.parseLong(s); 77 | } catch (NumberFormatException e) { 78 | Log.e("InfiniteBannerView", e.getMessage()); 79 | } 80 | } 81 | a.recycle(); 82 | } 83 | mScroller = new Scroller(context); 84 | ViewConfiguration config = ViewConfiguration.get(context); 85 | mTouchSlop = config.getScaledPagingTouchSlop(); 86 | mMaxVelocity = config.getScaledMinimumFlingVelocity(); 87 | } 88 | 89 | @Override 90 | protected void onAttachedToWindow() { 91 | super.onAttachedToWindow(); 92 | if (mAdapter != null) { 93 | mAdapter.registerDataSetObserver(mDataObserver); 94 | } 95 | startLoopIfNeeded(); 96 | mIsAttachToWindow = true; 97 | } 98 | 99 | @Override 100 | protected void onDetachedFromWindow() { 101 | super.onDetachedFromWindow(); 102 | if (mAdapter != null) { 103 | mAdapter.unregisterDataSetObserver(mDataObserver); 104 | } 105 | dispose(); 106 | mIsAttachToWindow = false; 107 | } 108 | 109 | @Override 110 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 111 | int sizeHeight = MeasureSpec.getSize(heightMeasureSpec); 112 | int modeHeight = MeasureSpec.getMode(heightMeasureSpec); 113 | int maxHeight = sizeHeight - getPaddingTop() - getPaddingBottom(); 114 | int childMaxWidth = (int) ((MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight()) * mForegroundWidthPercent) - mDividerWidth; 115 | int height = 0; 116 | for (int i = 0; i < getChildCount(); i++) { 117 | View child = getChildAt(i); 118 | measureChild(child, MeasureSpec.makeMeasureSpec(childMaxWidth, MeasureSpec.EXACTLY), heightMeasureSpec); 119 | height = Math.min(Math.max(height, child.getMeasuredHeight()), maxHeight); 120 | } 121 | setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), 122 | modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height + getPaddingTop() + getPaddingBottom()); 123 | } 124 | 125 | @Override 126 | protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 127 | if (getChildCount() == 0 || mAdapter == null) { 128 | return; 129 | } 130 | int outsideLength = (int) (getMeasuredWidth() * (1f - mForegroundWidthPercent) / 2); 131 | int periodLength = getPeriodLength(getMeasuredWidth()); 132 | if (mPager.isSkippingPosition()) { 133 | // refresh the layout after reset 134 | int head = mPager.mCurrentPosition - getDepthWithCache(); 135 | int tail = mPager.mCurrentPosition + getDepthWithCache(); 136 | while (head <= tail) { 137 | if (head == tail) { 138 | childLayout(getViewOnPosition(head), periodLength, outsideLength, head); 139 | } else { 140 | childLayout(getViewOnPosition(head), periodLength, outsideLength, head); 141 | childLayout(getViewOnPosition(tail), periodLength, outsideLength, tail); 142 | } 143 | head++; 144 | tail--; 145 | } 146 | } else if (mPager.isPreviousPosition()) { 147 | // scroll to the previous position 148 | childLayout(getViewOnPosition(mPager.mPositionLastRelayout + getDepthWithCache()), 149 | periodLength, outsideLength, mPager.mPositionLastRelayout - getDepthWithCache() - 1); 150 | } else if (mPager.isNextPosition()) { 151 | // scroll to the next position 152 | childLayout(getViewOnPosition(mPager.mPositionLastRelayout - getDepthWithCache()), 153 | periodLength, outsideLength, mPager.mPositionLastRelayout + getDepthWithCache() + 1); 154 | } 155 | mPager.recordWhenRelayout(); 156 | } 157 | 158 | private void childLayout(final View child, int periodLength, int outsideLength, int page) { 159 | if (child == null) { 160 | return; 161 | } 162 | final int index = getLoopIndex(page); 163 | if (index >= 0) { 164 | int childX = outsideLength + page * periodLength; 165 | child.layout( 166 | childX, 167 | 0, 168 | childX + periodLength - mDividerWidth, 169 | getMeasuredHeight()); 170 | mAdapter.bind(child, index); 171 | } else { 172 | child.layout(0, 0, 0, 0); 173 | } 174 | } 175 | 176 | @Override 177 | public void computeScroll() { 178 | if (mScroller.computeScrollOffset()) { 179 | int scrollX = mScroller.getCurrX(); 180 | scrollTo(scrollX, mScroller.getCurrY()); 181 | invalidate(); 182 | } 183 | } 184 | 185 | @Override 186 | protected void onScrollChanged(int l, int t, int oldl, int oldt) { 187 | super.onScrollChanged(l, t, oldl, oldt); 188 | 189 | if (getItemCount() > 0) { 190 | int periodLength = getPeriodLength(getWidth()); 191 | int page = l / periodLength; 192 | int positionOffsetPixels = l % periodLength; 193 | if (l < 0){ 194 | page -= 1; 195 | positionOffsetPixels += periodLength; 196 | } 197 | float positionOffset = (float) positionOffsetPixels / (float) periodLength; 198 | onPageScrolledInternal(page, positionOffset, positionOffsetPixels); 199 | } 200 | } 201 | 202 | @SuppressLint("ClickableViewAccessibility") 203 | @Override 204 | public boolean onTouchEvent(MotionEvent ev) { 205 | int x = (int) ev.getX(); 206 | int y = (int) ev.getY(); 207 | switch (ev.getAction()) { 208 | case MotionEvent.ACTION_DOWN: 209 | if (!mScroller.isFinished() && !isManuallyScrollLocked()) { 210 | mScroller.abortAnimation(); 211 | } 212 | mLastX = mLastDownX = x; 213 | mLastDownY = y; 214 | mIsTouching = true; 215 | break; 216 | case MotionEvent.ACTION_MOVE: 217 | if (!isManuallyScrollLocked()) { 218 | int dx = mLastX - x; 219 | if (isCurrentScrollAllowed(mPager.mCurrentPosition, dx > 0)) { 220 | scrollBy(dx, 0); 221 | } 222 | if (Math.abs(mLastDownX - x) > 20) { 223 | requestDisallowInterceptTouchEvent(true); 224 | } 225 | } 226 | mLastX = x; 227 | break; 228 | case MotionEvent.ACTION_OUTSIDE: 229 | case MotionEvent.ACTION_CANCEL: 230 | if (x != mLastDownX) { 231 | slowScrollToPage(); 232 | } 233 | touchFinished(); 234 | break; 235 | case MotionEvent.ACTION_UP: 236 | float outsideEachPercent = (1f - mForegroundWidthPercent) / 2; 237 | if (Math.abs(mLastDownX - x) < 20 238 | && Math.abs(mLastDownY - y) < 20 239 | && !performClick()) { 240 | if (x > getWidth() * outsideEachPercent && x < getWidth() * (1 - outsideEachPercent)) { 241 | handleClick(); 242 | } else if (!isManuallyScrollLocked()) { 243 | slowScrollToPage(); 244 | } 245 | } else if (!isManuallyScrollLocked()) { 246 | handleScroll(x); 247 | } 248 | touchFinished(); 249 | break; 250 | default: 251 | mIsTouching = false; 252 | break; 253 | } 254 | return true; 255 | } 256 | 257 | private void handleScroll(int x) { 258 | if (x - mLastDownX > 50) { 259 | goPreviousPage(); 260 | } else if (mLastDownX - x > 50) { 261 | goNextPage(); 262 | } else { 263 | slowScrollToPage(); 264 | } 265 | } 266 | 267 | private void touchFinished() { 268 | mIsTouching = false; 269 | mLastTouchTime = System.currentTimeMillis(); 270 | } 271 | 272 | private void handleClick() { 273 | if (mOnItemClickListener != null && getItemCount() > 0) { 274 | int periodLength = getPeriodLength(getWidth()); 275 | int page = getScrollX() / periodLength; 276 | if (getScrollX() % periodLength > periodLength / 2) { 277 | page++; 278 | } else if (getScrollX() % periodLength < -periodLength / 2){ 279 | page--; 280 | } 281 | mOnItemClickListener.click(this, getLoopIndex(page)); 282 | } 283 | } 284 | 285 | private void slowScrollToPage() { 286 | int periodLength = getPeriodLength(getWidth()); 287 | int whichPage = (getScrollX() + periodLength / 2) / periodLength; 288 | scrollToPage(whichPage); 289 | } 290 | 291 | private int getPeriodLength(int width) { 292 | return (int) (width * mForegroundWidthPercent) + mDividerWidth; 293 | } 294 | 295 | private void scrollToPage(int indexPage) { 296 | int loopIndex = getLoopIndex(indexPage); 297 | if (loopIndex == mPager.mInitialPosition && Math.abs(getScrollX()) > MAX_SCROLL_X) { 298 | reset(); 299 | return; 300 | } 301 | int periodLength = getPeriodLength(getWidth()); 302 | if (mPager.mCurrentPosition != indexPage) { 303 | long currentTime = System.currentTimeMillis(); 304 | // If it scroll too fast, just go back to the current position or it looks weird. 305 | boolean changeable = Math.abs(getScrollX() - mPager.mCurrentPosition * periodLength) <= 2 * periodLength 306 | && currentTime - mLastScrollTime > 300; 307 | if (changeable) { 308 | mPager.updateCurrentPosition(indexPage); 309 | mLastScrollTime = currentTime; 310 | if (!mOnPageChangeListeners.isEmpty()) { 311 | for (OnPageChangeListener onPageChangeListener : mOnPageChangeListeners) { 312 | onPageChangeListener.onPageSelected(loopIndex); 313 | } 314 | } 315 | } 316 | } 317 | int dx = mPager.mCurrentPosition * periodLength - getScrollX(); 318 | mScroller.startScroll(getScrollX(), 0, dx, 0, Math.abs(dx)); 319 | requestLayout(); 320 | } 321 | 322 | public void onPageScrolledInternal(int position, float positionOffset, int positionOffsetPixels) { 323 | if (!mOnPageChangeListeners.isEmpty()) { 324 | for (OnPageChangeListener onPageChangeListener : mOnPageChangeListeners) { 325 | onPageChangeListener.onPageScrolled(getLoopIndex(position), positionOffset, positionOffsetPixels); 326 | } 327 | } 328 | if (mPageTransformer != null) { 329 | transform(position, 1f - positionOffset); 330 | transform(position + 1, positionOffset); 331 | transform(position - 1, 0); 332 | transform(position + 2, 0); 333 | } 334 | } 335 | 336 | private void transform(int position, float transformPos) { 337 | View child = getViewOnPosition(position); 338 | if (child != null && getWidth() > 0) { 339 | mPageTransformer.transformPage(child, transformPos); 340 | } 341 | } 342 | 343 | public void setInitPosition(int position) { 344 | mPager.initPosition(position); 345 | reset(); 346 | } 347 | 348 | public int getInitPostion() { 349 | return mPager.mInitialPosition; 350 | } 351 | 352 | public int getCurrentPosition() { 353 | return mPager.mCurrentPosition; 354 | } 355 | 356 | public boolean isReverse() { 357 | return mIsReverse; 358 | } 359 | 360 | /** 361 | * @param reverse 362 | * false:from right to left 363 | * true:from left to right 364 | */ 365 | public void setReverse(boolean reverse) { 366 | mIsReverse = reverse; 367 | } 368 | 369 | private boolean isManuallyScrollLocked() { 370 | return mIsManuallyScrollLocked || getItemCount() <= 1; 371 | } 372 | 373 | /** 374 | * The manually scrolling will be locked or not 375 | * @param locked 376 | */ 377 | public void setManuallyScrollLocked(boolean locked) { 378 | mIsManuallyScrollLocked = locked; 379 | } 380 | 381 | public boolean isAutoScroll() { 382 | return mIsAutoScroll; 383 | } 384 | 385 | /** 386 | * It will automatically scroll or not after the data is loaded 387 | * @param autoScroll 388 | */ 389 | public void setAutoScroll(boolean autoScroll) { 390 | mIsAutoScroll = autoScroll; 391 | } 392 | 393 | /** 394 | * Scroll to the next position 395 | */ 396 | public void goNextPage() { 397 | if (isCurrentScrollAllowed(mPager.mCurrentPosition, true)) { 398 | scrollToPage(mPager.mCurrentPosition + 1); 399 | } 400 | } 401 | 402 | /** 403 | * Scroll to the previous position 404 | */ 405 | public void goPreviousPage() { 406 | if (isCurrentScrollAllowed(mPager.mCurrentPosition, false)) { 407 | scrollToPage(mPager.mCurrentPosition - 1); 408 | } 409 | } 410 | 411 | /** 412 | * Resume the scrolling animation 413 | */ 414 | public void resumeLoop() { 415 | dispose(); 416 | if (getItemCount() > 1) { 417 | loop(); 418 | } 419 | } 420 | 421 | /** 422 | * Pause the scrolling animation 423 | */ 424 | public void pauseLoop() { 425 | dispose(); 426 | } 427 | 428 | private boolean isCurrentScrollAllowed(int position, boolean forward) { 429 | return mScrollIntercepter == null || !mScrollIntercepter.onScrollIntercept(position, forward); 430 | } 431 | 432 | private View getViewOnPosition(int position) { 433 | int index = getLoopIndex(getChildCount(), position); 434 | return mViewsMap.get(index); 435 | } 436 | 437 | private void loop(){ 438 | mHandler.postDelayed(new Runnable() { 439 | @Override 440 | public void run() { 441 | if (!mIsTouching && System.currentTimeMillis() - mLastTouchTime > mLoopInterval / 2) { 442 | if (mIsReverse) { 443 | goPreviousPage(); 444 | } else { 445 | goNextPage(); 446 | } 447 | } 448 | loop(); 449 | } 450 | }, mLoopInterval); 451 | } 452 | 453 | private void dispose() { 454 | mHandler.removeCallbacksAndMessages(null); 455 | } 456 | 457 | private void reset() { 458 | relayoutAllViews(); 459 | mPager.reset(); 460 | post(new Runnable() { 461 | @Override 462 | public void run() { 463 | int periodLength = getPeriodLength(getWidth()); 464 | scrollTo(mPager.mInitialPosition * periodLength, 0); 465 | requestLayout(); 466 | if (!mOnPageChangeListeners.isEmpty()) { 467 | for (OnPageChangeListener onPageChangeListener : mOnPageChangeListeners) { 468 | onPageChangeListener.onPageSelected(mPager.mInitialPosition); 469 | } 470 | } 471 | onPageScrolledInternal(mPager.mInitialPosition, 0, 0); 472 | startLoopIfNeeded(); 473 | } 474 | }); 475 | } 476 | 477 | private void startLoopIfNeeded() { 478 | if (getItemCount() > 1 && mIsAutoScroll) { 479 | resumeLoop(); 480 | } 481 | } 482 | 483 | private void relayoutAllViews() { 484 | removeAllViewsInLayout(); 485 | int count = getItemCount(); 486 | for (int i = 0; i <= getDepthWithCache() * 2; i++) { 487 | View view = mViewsMap.get(i); 488 | if (view == null) { 489 | view = mAdapter.makeView(this); 490 | mViewsMap.put(i, view); 491 | } 492 | super.addView(view); 493 | } 494 | } 495 | 496 | /** 497 | * @return The layers that will be re-loaded 498 | */ 499 | private int getDepthWithCache() { 500 | return mForegroundWidthPercent < 1f ? 3 : 2; 501 | } 502 | 503 | private int getLoopIndex(int index) { 504 | return getLoopIndex(getItemCount(), index); 505 | } 506 | 507 | private int getLoopIndex(int totalCount, int index) { 508 | if (totalCount == 0){ 509 | return -1; 510 | } 511 | return index >= 0 ? index % totalCount : totalCount + (index + 1) % totalCount - 1; 512 | } 513 | 514 | public AbsBannerAdapter getAdapter() { 515 | return mAdapter; 516 | } 517 | 518 | public void setAdapter(AbsBannerAdapter adapter) { 519 | if (mAdapter != null) { 520 | mAdapter.unregisterDataSetObserver(mDataObserver); 521 | } 522 | mAdapter = adapter; 523 | if (mIsAttachToWindow) { 524 | mAdapter.registerDataSetObserver(mDataObserver); 525 | } 526 | reset(); 527 | } 528 | 529 | public ScrollIntercepter getScrollIntercepter() { 530 | return mScrollIntercepter; 531 | } 532 | 533 | public void setScrollIntercepter(ScrollIntercepter scrollIntercepter) { 534 | mScrollIntercepter = scrollIntercepter; 535 | } 536 | 537 | public void setPageTransformer(PageTransformer pageTransformer) { 538 | mPageTransformer = pageTransformer; 539 | } 540 | 541 | public OnItemClickListener getOnItemClickListener() { 542 | return mOnItemClickListener; 543 | } 544 | 545 | public void setOnItemClickListener(OnItemClickListener onItemClickListener) { 546 | mOnItemClickListener = onItemClickListener; 547 | } 548 | 549 | public void addOnPageChangeListener(OnPageChangeListener onPageChangeListener) { 550 | mOnPageChangeListeners.add(onPageChangeListener); 551 | } 552 | 553 | public void removeOnPageChangeListener(OnPageChangeListener onPageChangeListener) { 554 | mOnPageChangeListeners.remove(onPageChangeListener); 555 | } 556 | 557 | public int getDividerWidth() { 558 | return mDividerWidth; 559 | } 560 | 561 | /** 562 | * Space between two items 563 | * @param dividerWidth 564 | */ 565 | public void setDividerWidth(int dividerWidth) { 566 | mDividerWidth = dividerWidth; 567 | } 568 | 569 | public float getForegroundWidthPercent() { 570 | return mForegroundWidthPercent; 571 | } 572 | 573 | /** 574 | * The width 575 | * @param foregroundWidthPercent 576 | */ 577 | public void setForegroundWidthPercent(float foregroundWidthPercent) { 578 | mForegroundWidthPercent = Math.max(Math.min(foregroundWidthPercent, 1f), 0.34f); 579 | } 580 | 581 | public long getLoopInterval() { 582 | return mLoopInterval; 583 | } 584 | 585 | /** 586 | * Time interval between automatically scrolling animations 587 | * @param loopInterval (millisecond) 588 | */ 589 | public void setLoopInterval(long loopInterval) { 590 | mLoopInterval = loopInterval; 591 | } 592 | 593 | private int getItemCount() { 594 | return mAdapter == null ? 0 : mAdapter.getCount(); 595 | } 596 | 597 | private DataSetObserver mDataObserver = new DataSetObserver() { 598 | @Override 599 | public void onChanged() { 600 | reset(); 601 | } 602 | 603 | @Override 604 | public void onInvalidated() { 605 | requestLayout(); 606 | } 607 | }; 608 | 609 | public static interface OnItemClickListener { 610 | void click(InfiniteBannerView view, int position); 611 | } 612 | 613 | public static interface OnPageChangeListener { 614 | // See OnPageChangeListener in ViewPager 615 | void onPageScrolled(int position, float positionOffset, int positionOffsetPixels); 616 | void onPageSelected(int position); 617 | } 618 | 619 | public static interface ScrollIntercepter { 620 | /** 621 | * @param position current 622 | * @param forward true:from right to left;false:from left to right 623 | * @return intercept or not 624 | */ 625 | boolean onScrollIntercept(int position, boolean forward); 626 | } 627 | 628 | public interface PageTransformer { 629 | // See PageTransformer in ViewPager 630 | void transformPage(View view, float arg); 631 | } 632 | 633 | private static class Pager { 634 | private int mInitialPosition = 0, mCurrentPosition; 635 | private int mPositionLastRelayout = Integer.MAX_VALUE; 636 | 637 | private void initPosition(int position) { 638 | mInitialPosition = position; 639 | mCurrentPosition = mInitialPosition; 640 | } 641 | 642 | private void reset() { 643 | mPositionLastRelayout = Integer.MAX_VALUE; 644 | mCurrentPosition = mInitialPosition; 645 | } 646 | 647 | private void updateCurrentPosition(int currentPosition) { 648 | mCurrentPosition = currentPosition; 649 | } 650 | 651 | private void recordWhenRelayout() { 652 | mPositionLastRelayout = mCurrentPosition; 653 | } 654 | 655 | private boolean isSkippingPosition() { 656 | return Math.abs(mPositionLastRelayout - mCurrentPosition) > 1; 657 | } 658 | 659 | private boolean isNextPosition() { 660 | return mCurrentPosition - mPositionLastRelayout == 1; 661 | } 662 | 663 | private boolean isPreviousPosition() { 664 | return mCurrentPosition - mPositionLastRelayout == -1; 665 | } 666 | } 667 | } -------------------------------------------------------------------------------- /library/src/main/res/values/attrs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /library/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | InfiniteBanner 3 | 4 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':library' 2 | --------------------------------------------------------------------------------