├── app ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ ├── colors.xml │ │ │ │ └── styles.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 │ │ │ ├── mipmap-anydpi-v26 │ │ │ │ ├── ic_launcher.xml │ │ │ │ └── ic_launcher_round.xml │ │ │ ├── drawable │ │ │ │ ├── banner_indicator_select.xml │ │ │ │ ├── banner_indicator_unselect.xml │ │ │ │ └── ic_launcher_background.xml │ │ │ ├── layout │ │ │ │ ├── lay_banner_item.xml │ │ │ │ └── activity_main.xml │ │ │ └── drawable-v24 │ │ │ │ └── ic_launcher_foreground.xml │ │ ├── java │ │ │ └── com │ │ │ │ └── wenjian │ │ │ │ └── loopbannerdemo │ │ │ │ ├── BannerEntity.kt │ │ │ │ ├── DataCenter.kt │ │ │ │ └── MainActivity.kt │ │ └── AndroidManifest.xml │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── wenjian │ │ │ └── loopbannerdemo │ │ │ └── ExampleUnitTest.kt │ └── androidTest │ │ └── java │ │ └── com │ │ └── wenjian │ │ └── loopbannerdemo │ │ └── ExampleInstrumentedTest.kt ├── proguard-rules.pro └── build.gradle ├── loopbanner ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ ├── ids.xml │ │ │ │ └── attrs.xml │ │ │ ├── drawable │ │ │ │ ├── indicator_unselect.xml │ │ │ │ ├── indicator_jd.xml │ │ │ │ ├── indicator_select.xml │ │ │ │ └── indicator_color_selector.xml │ │ │ └── layout │ │ │ │ └── lay_internal_img.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── com │ │ │ └── wenjian │ │ │ └── loopbanner │ │ │ ├── AdapterHelper.java │ │ │ ├── SimpleImageAdapter.java │ │ │ ├── indicator │ │ │ ├── IndicatorAdapter.java │ │ │ ├── SelectDrawableAdapter.java │ │ │ └── JDIndicatorAdapter.java │ │ │ ├── LoopScroller.java │ │ │ ├── transformer │ │ │ └── ScalePageTransformer.java │ │ │ ├── Tools.java │ │ │ ├── LoopAdapter.java │ │ │ └── LoopBanner.java │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── wenjian │ │ │ └── loopbanner │ │ │ └── ExampleUnitTest.java │ └── androidTest │ │ └── java │ │ └── com │ │ └── wenjian │ │ └── loopbanner │ │ └── ExampleInstrumentedTest.java ├── proguard-rules.pro └── build.gradle ├── settings.gradle ├── resource ├── demo.gif ├── download.png └── qq_group.jpg ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── .gitignore ├── gradlew.bat ├── gradlew ├── LICENSE └── README.md /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /loopbanner/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app',":loopbanner" 2 | -------------------------------------------------------------------------------- /resource/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wenjiangit/LoopBanner/HEAD/resource/demo.gif -------------------------------------------------------------------------------- /resource/download.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wenjiangit/LoopBanner/HEAD/resource/download.png -------------------------------------------------------------------------------- /resource/qq_group.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wenjiangit/LoopBanner/HEAD/resource/qq_group.jpg -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wenjiangit/LoopBanner/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | LoopBannerDemo 3 | 4 | -------------------------------------------------------------------------------- /loopbanner/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | LoopBanner 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wenjiangit/LoopBanner/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wenjiangit/LoopBanner/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wenjiangit/LoopBanner/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wenjiangit/LoopBanner/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wenjiangit/LoopBanner/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wenjiangit/LoopBanner/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wenjiangit/LoopBanner/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /loopbanner/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wenjiangit/LoopBanner/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wenjiangit/LoopBanner/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wenjiangit/LoopBanner/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /loopbanner/src/main/res/values/ids.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /app/src/main/java/com/wenjian/loopbannerdemo/BannerEntity.kt: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbannerdemo 2 | 3 | /** 4 | * Description: BannerEntity 5 | * Date: 2018/12/7 6 | * 7 | * @author jian.wen@ubtrobot.com 8 | */ 9 | data class BannerEntity(val id: Int, val url: String,val title:String) 10 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #008577 4 | #00574B 5 | #D81B60 6 | #80000000 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /loopbanner/src/main/res/drawable/indicator_unselect.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/banner_indicator_select.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /loopbanner/src/main/res/drawable/indicator_jd.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/banner_indicator_unselect.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /loopbanner/src/main/res/drawable/indicator_select.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /loopbanner/src/main/res/layout/lay_internal_img.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/com/wenjian/loopbannerdemo/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbannerdemo 2 | 3 | import org.junit.Test 4 | 5 | import org.junit.Assert.* 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * See [testing documentation](http://d.android.com/tools/testing). 11 | */ 12 | class ExampleUnitTest { 13 | @Test 14 | fun addition_isCorrect() { 15 | assertEquals(4, 2 + 2) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /loopbanner/src/test/java/com/wenjian/loopbanner/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbanner; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /loopbanner/src/main/res/drawable/indicator_color_selector.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/wenjian/loopbannerdemo/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbannerdemo 2 | 3 | import android.support.test.InstrumentationRegistry 4 | import android.support.test.runner.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getTargetContext() 22 | assertEquals("com.wenjian.loopbannerdemo", appContext.packageName) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /loopbanner/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 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx1536m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # Kotlin code style for this project: "official" or "obsolete": 15 | kotlin.code.style=official 16 | -------------------------------------------------------------------------------- /loopbanner/src/androidTest/java/com/wenjian/loopbanner/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbanner; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumented test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.wenjian.loopbanner.test", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/res/layout/lay_banner_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 13 | 14 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /loopbanner/src/main/java/com/wenjian/loopbanner/AdapterHelper.java: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbanner; 2 | 3 | import android.support.annotation.NonNull; 4 | import android.view.View; 5 | import android.view.ViewGroup; 6 | 7 | class AdapterHelper { 8 | 9 | private int pageMargin; 10 | private int lrMargin; 11 | 12 | AdapterHelper(int pageMargin, int lrMargin) { 13 | this.pageMargin = pageMargin; 14 | this.lrMargin = lrMargin; 15 | } 16 | 17 | void onCreateViewHolder(@NonNull ViewGroup parent, View view) { 18 | ViewGroup.LayoutParams lp = view.getLayoutParams(); 19 | lp.width = parent.getWidth() - lrMargin * 2; 20 | view.setLayoutParams(lp); 21 | } 22 | 23 | void onBindViewHolder(@NonNull LoopAdapter.ViewHolder holder) { 24 | final ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) holder.itemView.getLayoutParams(); 25 | lp.leftMargin = pageMargin / 2; 26 | lp.rightMargin = pageMargin / 2; 27 | holder.itemView.setLayoutParams(lp); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /app/src/main/java/com/wenjian/loopbannerdemo/DataCenter.kt: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbannerdemo 2 | 3 | /** 4 | * Description: DataCenter 5 | * Date: 2018/12/7 6 | * 7 | * @author jian.wen@ubtrobot.com 8 | */ 9 | 10 | object DataCenter { 11 | fun loadImages() = loadEntities().map { it.url } 12 | 13 | 14 | fun loadEntities() = arrayListOf().apply { 15 | add(BannerEntity(0,"http://www.wanandroid.com/blogimgs/ab17e8f9-6b79-450b-8079-0f2287eb6f0f.png","看看别人的面经,搞定面试")) 16 | add(BannerEntity(1,"http://www.wanandroid.com/blogimgs/fb0ea461-e00a-482b-814f-4faca5761427.png","兄弟,要不要挑个项目学习下")) 17 | add(BannerEntity(2,"http://www.wanandroid.com/blogimgs/62c1bd68-b5f3-4a3c-a649-7ca8c7dfabe6.png","我们新增了一个常用导航Tab~")) 18 | add(BannerEntity(3,"http://www.wanandroid.com/blogimgs/00f83f1d-3c50-439f-b705-54a49fc3d90d.jpg","公众号文章列表强势上线")) 19 | add(BannerEntity(4,"http://www.wanandroid.com/blogimgs/90cf8c40-9489-4f9d-8936-02c9ebae31f0.png","JSON工具")) 20 | // add(BannerEntity(0,"http://www.wanandroid.com/blogimgs/acc23063-1884-4925-bdf8-0b0364a7243e.png","微信文章合集")) 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /loopbanner/src/main/java/com/wenjian/loopbanner/SimpleImageAdapter.java: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbanner; 2 | 3 | import android.view.View; 4 | import android.widget.ImageView; 5 | 6 | import com.bumptech.glide.Glide; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * Description: SimpleImageAdapter 12 | * Date: 2018/12/4 13 | * 14 | * @author jian.wen@ubtrobot.com 15 | */ 16 | class SimpleImageAdapter extends LoopAdapter { 17 | 18 | SimpleImageAdapter(List data) { 19 | super(data); 20 | } 21 | 22 | @Override 23 | public void onBindView(ViewHolder holder, String data, final int position) { 24 | ImageView itemView = (ImageView) holder.itemView; 25 | Glide.with(itemView.getContext()) 26 | .load(data) 27 | .into(itemView); 28 | if (mClickListener != null) { 29 | holder.itemView.setOnClickListener(new View.OnClickListener() { 30 | @Override 31 | public void onClick(View v) { 32 | mClickListener.onPageClick(v, position); 33 | } 34 | }); 35 | } 36 | 37 | } 38 | 39 | 40 | } 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the ART/Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | out/ 15 | 16 | # Gradle files 17 | .gradle/ 18 | build/ 19 | .idea/ 20 | 21 | # Local configuration file (sdk path, etc) 22 | local.properties 23 | 24 | # Proguard folder generated by Eclipse 25 | proguard/ 26 | 27 | # Log Files 28 | *.log 29 | 30 | # Android Studio Navigation editor temp files 31 | .navigation/ 32 | 33 | # Android Studio captures folder 34 | captures/ 35 | 36 | # IntelliJ 37 | *.iml 38 | .idea/workspace.xml 39 | .idea/tasks.xml 40 | .idea/gradle.xml 41 | .idea/assetWizardSettings.xml 42 | .idea/dictionaries 43 | .idea/libraries 44 | .idea/caches 45 | 46 | # Keystore files 47 | # Uncomment the following line if you do not want to check your keystore files in. 48 | #*.jks 49 | 50 | # External native build folder generated in Android Studio 2.2 and later 51 | .externalNativeBuild 52 | 53 | # Google Services (e.g. APIs or Firebase) 54 | google-services.json 55 | 56 | # Freeline 57 | freeline.py 58 | freeline/ 59 | freeline_project_description.json 60 | 61 | # fastlane 62 | fastlane/report.xml 63 | fastlane/Preview.html 64 | fastlane/screenshots 65 | fastlane/test_output 66 | fastlane/readme.md 67 | -------------------------------------------------------------------------------- /loopbanner/src/main/java/com/wenjian/loopbanner/indicator/IndicatorAdapter.java: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbanner.indicator; 2 | 3 | import android.graphics.drawable.Drawable; 4 | import android.view.View; 5 | import android.widget.LinearLayout; 6 | 7 | /** 8 | * Description: IndicatorAdapter 9 | * Date: 2018/12/6 10 | * 11 | * @author jian.wen@ubtrobot.com 12 | */ 13 | public interface IndicatorAdapter { 14 | 15 | /** 16 | * 添加子indicator 17 | * 18 | * @param container 父布局 19 | * @param drawable 配置的Drawable 20 | * @param size 配置的指示器大小 21 | * @param margin 配置的指示器margin值 22 | */ 23 | void addIndicator(LinearLayout container, Drawable drawable, int size, int margin); 24 | 25 | /** 26 | * 应用选中效果 27 | * 28 | * @param prev 上一个 29 | * @param current 当前 30 | * @param reverse 是否逆向滑动 31 | */ 32 | void applySelectState(View prev, View current, boolean reverse); 33 | 34 | /** 35 | * 应用为选中效果 36 | * 37 | * @param indicator 指示器 38 | */ 39 | void applyUnSelectState(View indicator); 40 | 41 | 42 | /** 43 | * 是否需要对某个位置进行特殊处理 44 | * 45 | * @param container 指示器容器 46 | * @param position 第一个或最后一个 47 | * @return 返回true代表处理好了 48 | */ 49 | boolean handleSpecial(LinearLayout container, int position); 50 | 51 | 52 | } 53 | -------------------------------------------------------------------------------- /loopbanner/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 27 5 | 6 | 7 | 8 | defaultConfig { 9 | minSdkVersion 14 10 | targetSdkVersion 27 11 | versionCode 1 12 | versionName "1.0" 13 | 14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 15 | 16 | } 17 | 18 | buildTypes { 19 | release { 20 | minifyEnabled false 21 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 22 | } 23 | } 24 | 25 | lintOptions { 26 | abortOnError false 27 | } 28 | 29 | } 30 | 31 | tasks.withType(Javadoc) { 32 | options { 33 | options.addStringOption('Xdoclint:none', '-quiet') 34 | options.addStringOption('encoding', 'UTF-8') 35 | options.addStringOption('charSet', 'UTF-8') 36 | } 37 | } 38 | 39 | 40 | dependencies { 41 | implementation fileTree(dir: 'libs', include: ['*.jar']) 42 | api "com.github.bumptech.glide:glide:4.8.0" 43 | implementation 'com.android.support:appcompat-v7:27.1.1' 44 | implementation 'com.android.support:recyclerview-v7:27.1.1' 45 | testImplementation 'junit:junit:4.12' 46 | androidTestImplementation 'com.android.support.test:runner:1.0.2' 47 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' 48 | } 49 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | apply plugin: 'kotlin-android' 4 | 5 | apply plugin: 'kotlin-android-extensions' 6 | 7 | android { 8 | compileSdkVersion 27 9 | defaultConfig { 10 | applicationId "com.wenjian.loopbannerdemo" 11 | minSdkVersion 14 12 | targetSdkVersion 27 13 | versionCode 1 14 | versionName "1.0" 15 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 16 | } 17 | buildTypes { 18 | release { 19 | minifyEnabled false 20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 21 | } 22 | } 23 | } 24 | 25 | dependencies { 26 | implementation fileTree(include: ['*.jar'], dir: 'libs') 27 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 28 | implementation 'com.android.support:appcompat-v7:27.1.1' 29 | implementation 'com.android.support:cardview-v7:27.1.1' 30 | implementation 'com.android.support.constraint:constraint-layout:1.1.3' 31 | implementation 'com.android.support:recyclerview-v7:27.1.1' 32 | testImplementation 'junit:junit:4.12' 33 | androidTestImplementation 'com.android.support.test:runner:1.0.2' 34 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' 35 | implementation "com.github.bumptech.glide:glide:3.7.0" 36 | implementation project(':loopbanner') 37 | // implementation 'com.github.wenjiangit:LoopBanner:1.0.3' 38 | } 39 | -------------------------------------------------------------------------------- /loopbanner/src/main/java/com/wenjian/loopbanner/LoopScroller.java: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbanner; 2 | 3 | import android.content.Context; 4 | import android.support.v4.view.ViewPager; 5 | import android.view.animation.Interpolator; 6 | import android.widget.Scroller; 7 | 8 | import java.lang.reflect.Field; 9 | 10 | /** 11 | * Description LoopScroller 12 | *

13 | * Date 2019/2/28 14 | * 15 | * @author wenjianes@163.com 16 | */ 17 | public class LoopScroller extends Scroller { 18 | 19 | private static final Interpolator sInterpolator = new Interpolator() { 20 | @Override 21 | public float getInterpolation(float t) { 22 | t -= 1.0f; 23 | return t * t * t * t * t + 1.0f; 24 | } 25 | }; 26 | 27 | private int mScrollerDuration; 28 | 29 | void setScrollerDuration(int mScrollerDuration) { 30 | this.mScrollerDuration = mScrollerDuration; 31 | } 32 | 33 | LoopScroller(Context context) { 34 | super(context, sInterpolator); 35 | } 36 | 37 | @Override 38 | public void startScroll(int startX, int startY, int dx, int dy) { 39 | this.startScroll(startX, startY, dx, dy, mScrollerDuration); 40 | } 41 | 42 | @Override 43 | public void startScroll(int startX, int startY, int dx, int dy, int duration) { 44 | super.startScroll(startX, startY, dx, dy, mScrollerDuration); 45 | } 46 | 47 | void linkViewPager(ViewPager viewPager) { 48 | try { 49 | Field mScroller = ViewPager.class.getDeclaredField("mScroller"); 50 | mScroller.setAccessible(true); 51 | mScroller.set(viewPager, this); 52 | } catch (Exception e) { 53 | e.printStackTrace(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 21 | 22 | 23 | 29 | 30 | 31 | 32 | 33 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /loopbanner/src/main/java/com/wenjian/loopbanner/transformer/ScalePageTransformer.java: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbanner.transformer; 2 | 3 | import android.support.annotation.NonNull; 4 | import android.support.v4.view.ViewPager; 5 | import android.view.View; 6 | 7 | /** 8 | * Description: ScalePageTransformer 9 | * Date: 2018/12/10 10 | * 11 | * @author jian.wen@ubtrobot.com 12 | */ 13 | public class ScalePageTransformer implements ViewPager.PageTransformer { 14 | 15 | private static final float DEFAULT_SCALE = 0.85f; 16 | private float mScale; 17 | 18 | public ScalePageTransformer(float mScale) { 19 | this.mScale = mScale; 20 | } 21 | 22 | public ScalePageTransformer() { 23 | this(DEFAULT_SCALE); 24 | } 25 | 26 | @Override 27 | public void transformPage(@NonNull View view, float position) { 28 | int width = view.getWidth(); 29 | int height = view.getHeight(); 30 | view.setPivotX(width / 2); 31 | view.setPivotY(height / 2); 32 | if (position < -1) { 33 | view.setScaleX(mScale); 34 | view.setScaleY(mScale); 35 | view.setPivotX(width); 36 | } else if (position <= 1) { 37 | if (position < 0) { 38 | float scaleFactor = (1 + position) * (1 - mScale) + mScale; 39 | view.setScaleX(scaleFactor); 40 | view.setScaleY(scaleFactor); 41 | view.setPivotX(width * (1 + (1 * -position))); 42 | } else { 43 | float scaleFactor = (1 - position) * (1 - mScale) + mScale; 44 | view.setScaleX(scaleFactor); 45 | view.setScaleY(scaleFactor); 46 | view.setPivotX(width * ((1 - position) * 1)); 47 | } 48 | } else { 49 | view.setPivotX(0); 50 | view.setScaleX(mScale); 51 | view.setScaleY(mScale); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /loopbanner/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 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /loopbanner/src/main/java/com/wenjian/loopbanner/indicator/SelectDrawableAdapter.java: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbanner.indicator; 2 | 3 | import android.graphics.drawable.Drawable; 4 | import android.view.View; 5 | import android.widget.ImageView; 6 | import android.widget.LinearLayout; 7 | 8 | /** 9 | * Description: SelectDrawableAdapter 10 | * Date: 2018/12/6 11 | * 12 | * @author jian.wen@ubtrobot.com 13 | */ 14 | public final class SelectDrawableAdapter implements IndicatorAdapter { 15 | 16 | private LinearLayout.LayoutParams mLayoutParams; 17 | 18 | @Override 19 | public void addIndicator(LinearLayout container, Drawable drawable, int size, int margin) { 20 | LinearLayout.LayoutParams layoutParams = generateLayoutParams(drawable, size, margin); 21 | ImageView image = new ImageView(container.getContext()); 22 | image.setImageDrawable(drawable); 23 | container.addView(image, layoutParams); 24 | } 25 | 26 | @Override 27 | public void applySelectState(View prev, View current, boolean reverse) { 28 | current.setSelected(true); 29 | current.requestLayout(); 30 | } 31 | 32 | private LinearLayout.LayoutParams generateLayoutParams(Drawable drawable, int size, int margin) { 33 | if (mLayoutParams == null) { 34 | final int minimumWidth = drawable.getMinimumWidth(); 35 | final int minimumHeight = drawable.getMinimumHeight(); 36 | LinearLayout.LayoutParams layoutParams; 37 | if (minimumWidth == 0 || minimumHeight == 0) { 38 | layoutParams = new LinearLayout.LayoutParams(size, size); 39 | } else { 40 | layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 41 | LinearLayout.LayoutParams.WRAP_CONTENT); 42 | } 43 | layoutParams.leftMargin = margin; 44 | mLayoutParams = layoutParams; 45 | } 46 | return mLayoutParams; 47 | } 48 | 49 | @Override 50 | public void applyUnSelectState(View indicator) { 51 | indicator.setSelected(false); 52 | indicator.requestLayout(); 53 | } 54 | 55 | @Override 56 | public boolean handleSpecial(LinearLayout container, int position) { 57 | return false; 58 | } 59 | 60 | 61 | } 62 | -------------------------------------------------------------------------------- /loopbanner/src/main/java/com/wenjian/loopbanner/Tools.java: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbanner; 2 | 3 | import android.content.Context; 4 | import android.support.annotation.NonNull; 5 | import android.util.Log; 6 | 7 | /** 8 | * Description: Tools 9 | * Date: 2018/12/4 10 | * 11 | * @author jian.wen@ubtrobot.com 12 | */ 13 | class Tools { 14 | 15 | private static boolean debug = false; 16 | 17 | private static final String TAG = "LoopBanner"; 18 | 19 | static void setDebug(boolean debug) { 20 | Tools.debug = debug; 21 | logD(TAG, "version: 1.0.5"); 22 | } 23 | 24 | static int dp2px(Context context, int dpValue) { 25 | float scale = context.getResources().getDisplayMetrics().density; 26 | return Math.round(dpValue * scale + 0.5f); 27 | } 28 | 29 | static void logD(String tag, String msg) { 30 | if (debug) { 31 | Log.d(tag, msg); 32 | } 33 | } 34 | 35 | static void logI(String tag, String msg) { 36 | if (debug) { 37 | Log.i(tag, msg); 38 | } 39 | } 40 | 41 | static void logE(String tag, String msg, Throwable throwable) { 42 | if (debug) { 43 | Log.e(tag, msg, throwable); 44 | } 45 | } 46 | 47 | /** 48 | * Ensures that an object reference passed as a parameter to the calling 49 | * method is not null. 50 | * 51 | * @param reference an object reference 52 | * @return the non-null reference that was validated 53 | * @throws NullPointerException if {@code reference} is null 54 | */ 55 | static @NonNull 56 | T checkNotNull(final T reference) { 57 | if (reference == null) { 58 | throw new NullPointerException(); 59 | } 60 | return reference; 61 | } 62 | 63 | /** 64 | * Ensures that an object reference passed as a parameter to the calling 65 | * method is not null. 66 | * 67 | * @param reference an object reference 68 | * @param errorMessage the exception message to use if the check fails; will 69 | * be converted to a string using {@link String#valueOf(Object)} 70 | * @return the non-null reference that was validated 71 | * @throws NullPointerException if {@code reference} is null 72 | */ 73 | static @NonNull 74 | T checkNotNull(final T reference, final Object errorMessage) { 75 | if (reference == null) { 76 | throw new NullPointerException(String.valueOf(errorMessage)); 77 | } 78 | return reference; 79 | } 80 | 81 | 82 | } 83 | -------------------------------------------------------------------------------- /loopbanner/src/main/java/com/wenjian/loopbanner/indicator/JDIndicatorAdapter.java: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbanner.indicator; 2 | 3 | import android.graphics.drawable.Drawable; 4 | import android.support.v4.content.ContextCompat; 5 | import android.support.v4.view.ViewCompat; 6 | import android.view.View; 7 | import android.widget.ImageView; 8 | import android.widget.LinearLayout; 9 | 10 | import com.wenjian.loopbanner.R; 11 | 12 | /** 13 | * Description: JDIndicatorAdapter 14 | * Date: 2018/12/6 15 | * 16 | * @author jian.wen@ubtrobot.com 17 | */ 18 | public class JDIndicatorAdapter implements IndicatorAdapter { 19 | 20 | private final int drawableId; 21 | 22 | private boolean initialed = false; 23 | private float mScale; 24 | 25 | public JDIndicatorAdapter(int drawableId) { 26 | this.drawableId = drawableId; 27 | } 28 | 29 | public JDIndicatorAdapter() { 30 | this(R.drawable.indicator_jd); 31 | } 32 | 33 | @Override 34 | public void addIndicator(LinearLayout container, Drawable drawable, int size, int margin) { 35 | drawable = ContextCompat.getDrawable(container.getContext(), drawableId); 36 | if (drawable == null) { 37 | throw new IllegalArgumentException("please provide valid drawableId"); 38 | } 39 | ImageView image = new ImageView(container.getContext()); 40 | ViewCompat.setBackground(image, drawable); 41 | LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 42 | LinearLayout.LayoutParams.WRAP_CONTENT); 43 | params.leftMargin = margin; 44 | container.addView(image, params); 45 | 46 | computeScale(drawable.getMinimumWidth(), margin); 47 | 48 | } 49 | 50 | @Override 51 | public void applySelectState(View prev, View current, boolean reverse) { 52 | prev.setPivotX(0); 53 | prev.setPivotY(prev.getHeight() >> 1); 54 | if (reverse) { 55 | current.animate().scaleX(1).setDuration(200).start(); 56 | } else { 57 | prev.animate().scaleX(mScale).setDuration(200).start(); 58 | } 59 | } 60 | 61 | @Override 62 | public void applyUnSelectState(View indicator) { 63 | 64 | } 65 | 66 | @Override 67 | public boolean handleSpecial(LinearLayout container, int position) { 68 | int childCount = container.getChildCount(); 69 | //对第一个和最后一个做特殊处理 70 | if (position == 0 || position == childCount - 1) { 71 | for (int i = 0; i < childCount; i++) { 72 | View childAt = container.getChildAt(i); 73 | childAt.setPivotX(0); 74 | childAt.setPivotY(childAt.getHeight() >> 1); 75 | //第一个 76 | if (position == 0) { 77 | childAt.animate().scaleX(1).setDuration(200).start(); 78 | } 79 | //最后一个 80 | else { 81 | if (i != childCount - 1) { 82 | childAt.animate().scaleX(mScale).setDuration(200).start(); 83 | } 84 | } 85 | } 86 | return true; 87 | } 88 | return false; 89 | } 90 | 91 | private void computeScale(int width, int margin) { 92 | if (!initialed) { 93 | mScale = width == 0 ? 2 : ((width + margin + width / 2) * 1f) / width; 94 | initialed = true; 95 | } 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /app/src/main/java/com/wenjian/loopbannerdemo/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbannerdemo 2 | 3 | import android.os.Bundle 4 | import android.os.Handler 5 | import android.support.v7.app.AppCompatActivity 6 | import android.widget.ImageView 7 | import android.widget.Toast 8 | import com.bumptech.glide.Glide 9 | import com.bumptech.glide.load.resource.bitmap.CenterCrop 10 | import com.bumptech.glide.load.resource.bitmap.RoundedCorners 11 | import com.bumptech.glide.request.RequestOptions 12 | import com.wenjian.loopbanner.LoopAdapter 13 | import kotlinx.android.synthetic.main.activity_main.* 14 | 15 | class MainActivity : AppCompatActivity() { 16 | companion object { 17 | private const val TAG = "MainActivity" 18 | } 19 | 20 | override fun onCreate(savedInstanceState: Bundle?) { 21 | super.onCreate(savedInstanceState) 22 | setContentView(R.layout.activity_main) 23 | //设置选中监听 24 | lb1.setOnPageSelectListener { 25 | // Log.d(TAG, "select = $it") 26 | } 27 | 28 | //设置是否自动轮播,默认为true 29 | lb1.setAutoLoop(false) 30 | 31 | //设置切换时长 32 | lb1.setTransformDuration(1000) 33 | 34 | //设置图片资源并添加page点击事件 35 | lb1.setImages(DataCenter.loadImages().take(2)) { _, position -> 36 | Toast.makeText(this, "position=$position", Toast.LENGTH_SHORT).show() 37 | } 38 | 39 | 40 | //仅仅设置图片资源 41 | // lb1.setImages(DataCenter.loadImages()) 42 | //设置指示器风格,有3种风格可选 43 | // lb1.setIndicatorStyle(LoopBanner.Style.NORMAL) 44 | // lb1.setIndicatorStyle(LoopBanner.Style.JD) 45 | // lb1.setIndicatorStyle(LoopBanner.Style.PILL) 46 | 47 | //设置中心page的左右边距 48 | lb2.setLrMargin(20) 49 | //设置page之间的间距 50 | lb2.pageMargin = 6 51 | 52 | //开启调试模式,有关键日志输出 53 | lb2.openDebug() 54 | //允许左右缩放,默认缩放比例为0.85 55 | lb2.enableScale() 56 | 57 | //直接设置adapter,默认的itemView是ImageView 58 | lb2.adapter = object : LoopAdapter(DataCenter.loadImages().take(3)) { 59 | override fun onBindView(holder: ViewHolder, data: String, position: Int) { 60 | val itemView = holder.itemView as ImageView 61 | Glide.with(holder.context) 62 | .load(data) 63 | .apply( 64 | //实现图片圆角 65 | RequestOptions() 66 | .transforms( 67 | CenterCrop(), RoundedCorners(20) 68 | ) 69 | ) 70 | .into(itemView) 71 | itemView.setOnClickListener { 72 | Toast.makeText(this@MainActivity, "position=$position", Toast.LENGTH_SHORT) 73 | .show() 74 | } 75 | } 76 | } 77 | 78 | //自定义布局 79 | lb3.adapter = MyAdapter() 80 | 81 | } 82 | 83 | override fun onStart() { 84 | super.onStart() 85 | 86 | Handler().postDelayed({ 87 | lb3.adapter?.setNewData(DataCenter.loadEntities()) 88 | 89 | }, 5000) 90 | 91 | } 92 | 93 | 94 | class MyAdapter : LoopAdapter(R.layout.lay_banner_item) { 95 | override fun onBindView(holder: ViewHolder, data: BannerEntity, position: Int) { 96 | val image = holder.getView(R.id.iv_image) 97 | 98 | Glide.with(holder.context) 99 | .load(data.url) 100 | .apply(RequestOptions.centerCropTransform()) 101 | .into(image) 102 | holder.setText(R.id.tv_title, data.title) 103 | 104 | holder.itemView.setOnClickListener { 105 | Toast.makeText(holder.context, "position=$position", Toast.LENGTH_SHORT).show() 106 | } 107 | } 108 | } 109 | 110 | 111 | } 112 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34 | 36 | 38 | 40 | 42 | 44 | 46 | 48 | 50 | 52 | 54 | 56 | 58 | 60 | 62 | 64 | 66 | 68 | 70 | 72 | 74 | 75 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /loopbanner/src/main/java/com/wenjian/loopbanner/LoopAdapter.java: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbanner; 2 | 3 | import android.content.Context; 4 | import android.graphics.Bitmap; 5 | import android.graphics.drawable.Drawable; 6 | import android.support.annotation.ColorInt; 7 | import android.support.annotation.DrawableRes; 8 | import android.support.annotation.IdRes; 9 | import android.support.annotation.NonNull; 10 | import android.support.annotation.StringRes; 11 | import android.support.v7.widget.RecyclerView; 12 | import android.util.SparseArray; 13 | import android.view.LayoutInflater; 14 | import android.view.View; 15 | import android.view.ViewGroup; 16 | import android.widget.FrameLayout; 17 | import android.widget.ImageView; 18 | import android.widget.TextView; 19 | 20 | 21 | import java.util.ArrayList; 22 | import java.util.List; 23 | 24 | /** 25 | * Description: LoopAdapter 26 | * Date: 2018/12/4 27 | * 28 | * @author jian.wen@ubtrobot.com 29 | */ 30 | public abstract class LoopAdapter extends RecyclerView.Adapter { 31 | 32 | private static final String TAG = "LoopAdapter"; 33 | private List mData; 34 | private int mLayoutId; 35 | private boolean mCanLoop = true; 36 | LoopBanner.OnPageClickListener mClickListener; 37 | 38 | private AdapterHelper mHelper; 39 | 40 | public LoopAdapter(List data, int layoutId) { 41 | mData = data == null ? new ArrayList() : data; 42 | mLayoutId = layoutId; 43 | } 44 | 45 | public LoopAdapter(List data) { 46 | this(data, -1); 47 | } 48 | 49 | public LoopAdapter(int layoutId) { 50 | this(new ArrayList(), layoutId); 51 | } 52 | 53 | public LoopAdapter() { 54 | this(new ArrayList(), -1); 55 | } 56 | 57 | void setHelper(AdapterHelper helper) { 58 | this.mHelper = helper; 59 | } 60 | 61 | @NonNull 62 | @Override 63 | public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { 64 | final View view = onCreateView(parent); 65 | mHelper.onCreateViewHolder(parent, view); 66 | return new ViewHolder(view); 67 | } 68 | 69 | 70 | @Override 71 | public void onBindViewHolder(@NonNull ViewHolder holder, int position) { 72 | mHelper.onBindViewHolder(holder); 73 | final int dataPosition = computePosition(position); 74 | onBindView(holder, mData.get(dataPosition), dataPosition); 75 | } 76 | 77 | 78 | @Override 79 | public int getItemCount() { 80 | final int size = mData.size(); 81 | if (size != 0) { 82 | return mCanLoop ? Integer.MAX_VALUE : size; 83 | } 84 | return size; 85 | } 86 | 87 | 88 | /** 89 | * 获取真实的数据个数 90 | */ 91 | public final int getDataSize() { 92 | return mData.size(); 93 | } 94 | 95 | private int computePosition(int position) { 96 | final int size = mData.size(); 97 | return size == 0 ? 0 : position % size; 98 | } 99 | 100 | /** 101 | * 子类可以复写此方法,添加自己的自定义View 102 | * 103 | * @param container ViewGroup 104 | * @return itemView 105 | */ 106 | @NonNull 107 | protected View onCreateView(@NonNull ViewGroup container) { 108 | Tools.logI(TAG, "onCreateView"); 109 | View view; 110 | if (mLayoutId != -1) { 111 | view = LayoutInflater.from(container.getContext()).inflate(mLayoutId, container, false); 112 | } else { 113 | view = LayoutInflater.from(container.getContext()).inflate(R.layout.lay_internal_img,container,false); 114 | } 115 | return view; 116 | } 117 | 118 | /** 119 | * 为每个page绑定数据 120 | * 121 | * @param holder ViewHolder 122 | * @param data 数据 123 | * @param position 数据真实位置 124 | */ 125 | protected abstract void onBindView(ViewHolder holder, T data, int position); 126 | 127 | /** 128 | * 设置数据集 129 | * 130 | * @param data List data 131 | */ 132 | public final void setNewData(List data) { 133 | mData = data != null ? data : new ArrayList(); 134 | notifyDataSetChanged(); 135 | } 136 | 137 | int getDataPosition(int position) { 138 | return computePosition(position); 139 | } 140 | 141 | void setOnPageClickListener(LoopBanner.OnPageClickListener listener) { 142 | this.mClickListener = listener; 143 | } 144 | 145 | void setCanLoop(boolean canLoop) { 146 | mCanLoop = canLoop; 147 | } 148 | 149 | public static final class ViewHolder extends RecyclerView.ViewHolder { 150 | 151 | private final SparseArray mViewList = new SparseArray<>(); 152 | 153 | ViewHolder(View itemView) { 154 | super(itemView); 155 | } 156 | 157 | @SuppressWarnings("unchecked") 158 | public T getView(@IdRes int viewId) { 159 | View view = mViewList.get(viewId); 160 | if (view == null) { 161 | view = itemView.findViewById(viewId); 162 | mViewList.put(viewId, view); 163 | } 164 | return (T) view; 165 | } 166 | 167 | public Context getContext() { 168 | return itemView.getContext(); 169 | } 170 | 171 | public View getItemView() { 172 | return itemView; 173 | } 174 | 175 | /** 176 | * Will set the text of a TextView. 177 | * 178 | * @param viewId The view id. 179 | * @param value The text to put in the text view. 180 | * @return The BaseViewHolder for chaining. 181 | */ 182 | public ViewHolder setText(@IdRes int viewId, CharSequence value) { 183 | TextView view = getView(viewId); 184 | view.setText(value); 185 | return this; 186 | } 187 | 188 | public ViewHolder setText(@IdRes int viewId, @StringRes int strId) { 189 | TextView view = getView(viewId); 190 | view.setText(strId); 191 | return this; 192 | } 193 | 194 | /** 195 | * Will set the image of an ImageView from a resource id. 196 | * 197 | * @param viewId The view id. 198 | * @param imageResId The image resource id. 199 | * @return The BaseViewHolder for chaining. 200 | */ 201 | public ViewHolder setImageResource(@IdRes int viewId, @DrawableRes int imageResId) { 202 | ImageView view = getView(viewId); 203 | view.setImageResource(imageResId); 204 | return this; 205 | } 206 | 207 | /** 208 | * Will set background color of a view. 209 | * 210 | * @param viewId The view id. 211 | * @param color A color, not a resource id. 212 | * @return The BaseViewHolder for chaining. 213 | */ 214 | public ViewHolder setBackgroundColor(@IdRes int viewId, @ColorInt int color) { 215 | View view = getView(viewId); 216 | view.setBackgroundColor(color); 217 | return this; 218 | } 219 | 220 | /** 221 | * Will set background of a view. 222 | * 223 | * @param viewId The view id. 224 | * @param backgroundRes A resource to use as a background. 225 | * @return The BaseViewHolder for chaining. 226 | */ 227 | public ViewHolder setBackgroundRes(@IdRes int viewId, @DrawableRes int backgroundRes) { 228 | View view = getView(viewId); 229 | view.setBackgroundResource(backgroundRes); 230 | return this; 231 | } 232 | 233 | /** 234 | * Will set text color of a TextView. 235 | * 236 | * @param viewId The view id. 237 | * @param textColor The text color (not a resource id). 238 | * @return The BaseViewHolder for chaining. 239 | */ 240 | public ViewHolder setTextColor(@IdRes int viewId, @ColorInt int textColor) { 241 | TextView view = getView(viewId); 242 | view.setTextColor(textColor); 243 | return this; 244 | } 245 | 246 | 247 | /** 248 | * Will set the image of an ImageView from a drawable. 249 | * 250 | * @param viewId The view id. 251 | * @param drawable The image drawable. 252 | * @return The BaseViewHolder for chaining. 253 | */ 254 | public ViewHolder setImageDrawable(@IdRes int viewId, Drawable drawable) { 255 | ImageView view = getView(viewId); 256 | view.setImageDrawable(drawable); 257 | return this; 258 | } 259 | 260 | /** 261 | * Add an action to set the image of an image view. Can be called multiple times. 262 | */ 263 | public ViewHolder setImageBitmap(@IdRes int viewId, Bitmap bitmap) { 264 | ImageView view = getView(viewId); 265 | view.setImageBitmap(bitmap); 266 | return this; 267 | } 268 | 269 | /** 270 | * Set a view visibility to VISIBLE (true) or GONE (false). 271 | * 272 | * @param viewId The view id. 273 | * @param visible True for VISIBLE, false for GONE. 274 | * @return The BaseViewHolder for chaining. 275 | */ 276 | public ViewHolder setGone(@IdRes int viewId, boolean visible) { 277 | View view = getView(viewId); 278 | view.setVisibility(visible ? View.VISIBLE : View.GONE); 279 | return this; 280 | } 281 | 282 | /** 283 | * Set a view visibility to VISIBLE (true) or INVISIBLE (false). 284 | * 285 | * @param viewId The view id. 286 | * @param visible True for VISIBLE, false for INVISIBLE. 287 | * @return The BaseViewHolder for chaining. 288 | */ 289 | public ViewHolder setVisible(@IdRes int viewId, boolean visible) { 290 | View view = getView(viewId); 291 | view.setVisibility(visible ? View.VISIBLE : View.INVISIBLE); 292 | return this; 293 | } 294 | } 295 | } 296 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | [![](https://www.jitpack.io/v/wenjiangit/LoopBanner.svg)](https://www.jitpack.io/#wenjiangit/LoopBanner) 3 | 4 | # LoopBanner 5 | 一个简单好用的超轻量的自动轮播控件,支持UI风格完全自定义 6 | 7 | ## 功能介绍 8 | 9 | - 支持自动无限轮播,无需手动开启和关闭,无需担心内存泄漏 10 | - 支持页面内容完全自定义 11 | - 支持自定义页面点击事件 12 | - 支持自定义指示器样式 13 | 14 | 基本上该有的都有,并且使用简单,只要你会用``ListView``或者``RecyclerView`` 15 | 16 | 如果对``LoopBanner``原理感兴趣可以查看[LoopBanner原理浅析](https://www.jianshu.com/p/a3f88f12ad1b) 17 | 18 | ## 效果图和Demo下载 19 | 20 | ![](https://github.com/wenjiangit/LoopBanner/blob/master/resource/demo.gif) 21 | 22 | 图片资源来源于鸿洋大神的[**wanandroid**](http://www.wanandroid.com/) 23 | 24 | 扫描二维码下载 25 | 26 | ![扫描二维码下载](https://github.com/wenjiangit/LoopBanner/blob/master/resource/download.png) 27 | 28 | [点击下载demo](https://fir.im/f68s) 29 | 30 | ## 使用介绍 31 | 32 | ### 1.添加Gradle依赖 33 | 34 | 在项目的``build.gradle``文件中添加``jitpack``仓库地址 35 | 36 | ```groovy 37 | allprojects { 38 | repositories { 39 | ... 40 | //添加下面的仓库地址 41 | maven { url "https://jitpack.io" } 42 | } 43 | } 44 | ``` 45 | 46 | 在``app``的``build.gradle``文件中添加``dependencies``: 47 | 48 | ```groovy 49 | dependencies { 50 | ... 51 | implementation 'com.github.wenjiangit:LoopBanner:1.1.1' 52 | } 53 | ``` 54 | 55 | 版本更新:[点击查看最新版本号](https://github.com/wenjiangit/LoopBanner/releases) 56 | 57 | ### 2.在xml布局资源中引用 58 | 59 | ```xml 60 | 68 | ``` 69 | 70 | 有关的属性定义后面再详细介绍 71 | 72 | ### 3.绑定数据 73 | 74 | 绑定数据有两种方式 75 | 76 | 1. 直接设置图片资源,并添加点击事件 77 | 78 | ```kotlin 79 | //设置图片资源并添加page点击事件 80 | lb1.setImages(DataCenter.loadImages()) { _, position -> 81 | Toast.makeText(this, "position=$position", Toast.LENGTH_SHORT).show() 82 | } 83 | ``` 84 | 85 | 当然如果你不需要点击事件,那就更简单了,如下: 86 | 87 | ```kotlin 88 | //直接绑定图片资源 89 | lb1.setImages(DataCenter.loadImages()) 90 | ``` 91 | 92 | 2. 通过``setAdapter``绑定数据 93 | 94 | ```kotlin 95 | //直接设置adapter,默认的itemView是ImageView 96 | lb2.adapter = object : LoopAdapter(DataCenter.loadImages()) { 97 | override fun onBindView(holder: ViewHolder, data: String, position: Int) { 98 | val itemView = holder.itemView as ImageView 99 | Glide.with(holder.context).load(data).into(itemView) 100 | itemView.setOnClickListener { 101 | Toast.makeText(this@MainActivity, "position=$position", Toast.LENGTH_SHORT).show() 102 | } 103 | } 104 | } 105 | ``` 106 | 107 | ``Adapter``的构建也很简单,只需要继承``LoopAdapter``,传入数据列表,并重写``onBindView``方法即可,在``onBindView``中可以设置点击事件,并绑定控件,与``RecylerView``的``onBindView``思想是一样的。 108 | 109 | 需要注意的是``LoopAdapter``接受两个参数,如下 110 | 111 | ```java 112 | public LoopAdapter(List data, int layoutId) { 113 | mData = data; 114 | mLayoutId = layoutId; 115 | } 116 | ``` 117 | 118 | ``layoutId``如果不传,默认的``holder.itemView``是``ImageView``,否则就是加载对应的布局而生成的``view``。如下: 119 | 120 | ```kotlin 121 | class MyAdapter(data: List) : LoopAdapter(data, R.layout.lay_banner_item) { 122 | override fun onBindView(holder: ViewHolder, data: BannerEntity, position: Int) { 123 | val image = holder.getView(R.id.iv_image) 124 | Glide.with(holder.context).load(data.url).into(image) 125 | holder.setText(R.id.tv_title,data.title) 126 | 127 | holder.itemView.setOnClickListener { 128 | Toast.makeText(holder.context, "position=$position", Toast.LENGTH_SHORT).show() 129 | } 130 | } 131 | } 132 | //设置Adapter 133 | lb3.adapter = MyAdapter(DataCenter.loadEntities()) 134 | ``` 135 | 136 | ``ViewHolder``提供getView方法获取对应的控件,与``holder.itemView.findViewById()``的效果是一样的,不过``getView``做了缓存,可以减少每次``findViewById``的时间。 137 | 138 | ### 4.设置指示器风格(可选) 139 | 140 | 1. 属性设置 141 | 142 | ````xml 143 | //普通风格,小圆点(默认样式) 144 | app:lb_indicatorStyle="normal" 145 | //京东app首页广告图指示器风格,挺独特的 146 | app:lb_indicatorStyle="jd" 147 | //小药丸风格,选中的小圆点变成小药丸 148 | app:lb_indicatorStyle="pill" 149 | ```` 150 | 151 | 2. 代码设置 152 | 153 | ```kotlin 154 | lb1.setIndicatorStyle(LoopBanner.Style.NORMAL) 155 | lb1.setIndicatorStyle(LoopBanner.Style.JD) 156 | lb1.setIndicatorStyle(LoopBanner.Style.PILL) 157 | ``` 158 | 159 | 到此为止,经过以上的设置已经可以实现市场上大部分的效果了。 160 | 161 | ## 高级设置 162 | 163 | 这部分适用于对于UI效果或者指示器风格有更高要求的人 164 | 165 | ### 1.自定义属性说明 166 | 167 | ```xml 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | ``` 212 | 213 | 每个属性都有详细注释,并且提供对应的代码设置api,建议通过api设置属性时,最好放在``setAdapter``方法调用之前,否则可能抛出异常. 214 | 215 | ### 2.指示器位置和样式 216 | 217 | 位置设置: 218 | 219 | ``lb_indicatorGravity``:定义指示器处于左下,中下,右下 220 | 221 | ``lb_indicatorParentMarginV``:定义指示器垂直向下的间距 222 | 223 | ``lb_indicatorParentMarginH``:定义指示器水平方向的间距,靠左还是靠右由``lb_indicatorGravity``决定 224 | 225 | 这3个属性配合使用基本上可以定位到父容器内的任何位置。 226 | 227 | 样式设置: 228 | 229 | ``lb_indicatorSelect``:选中的drawable资源 230 | 231 | ``lb_indicatorUnSelect``:未选中的drawable资源 232 | 233 | 当然也可以通过代码设置,如下: 234 | 235 | ``` 236 | /** 237 | * 设置指示器资源 238 | * 239 | * @param selectRes 选中 240 | * @param unSelectRes 未选中 241 | */ 242 | public void setIndicatorResource(@DrawableRes int selectRes, @DrawableRes int unSelectRes) { 243 | this.setIndicatorResource(selectRes, unSelectRes, true); 244 | } 245 | ``` 246 | 247 | **注意**:如果``drawable``资源设置了宽高,就会使用``drawable``的宽高,如下 248 | 249 | ```xml 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | ``` 260 | 261 | 如果没有设置宽高,就会使用````属性值. 262 | 263 | 这两个配合使用可以实现80%的效果,另外的20%需要通过以下方式实现 264 | 265 | 实现``IndicatorAdapter``接口,每个方法的作用可以看注释 266 | 267 | ```java 268 | public interface IndicatorAdapter { 269 | 270 | /** 271 | * 添加子indicator 272 | * 273 | * @param container 父布局 274 | * @param drawable 配置的Drawable 275 | * @param size 配置的指示器大小 276 | * @param margin 配置的指示器margin值 277 | */ 278 | void addIndicator(LinearLayout container, Drawable drawable, int size, int margin); 279 | 280 | /** 281 | * 应用选中效果 282 | * 283 | * @param prev 上一个 284 | * @param current 当前 285 | * @param reverse 是否逆向滑动 286 | */ 287 | void applySelectState(View prev, View current, boolean reverse); 288 | 289 | /** 290 | * 应用为选中效果 291 | * 292 | * @param indicator 指示器 293 | */ 294 | void applyUnSelectState(View indicator); 295 | 296 | 297 | /** 298 | * 是否需要对某个位置进行特殊处理 299 | * 300 | * @param container 指示器容器 301 | * @param position 第一个或最后一个 302 | * @return 返回true代表处理好了 303 | */ 304 | boolean handleSpecial(LinearLayout container, int position); 305 | 306 | 307 | } 308 | ``` 309 | 310 | 以下是默认的实现``SelectDrawableAdapter``,通过``view``的``select``状态切换指示器状态,大家可以参考下 311 | 312 | ```java 313 | public final class SelectDrawableAdapter implements IndicatorAdapter { 314 | 315 | private LinearLayout.LayoutParams mLayoutParams; 316 | 317 | @Override 318 | public void addIndicator(LinearLayout container, Drawable drawable, int size, int margin) { 319 | LinearLayout.LayoutParams layoutParams = generateLayoutParams(drawable, size, margin); 320 | ImageView image = new ImageView(container.getContext()); 321 | image.setImageDrawable(drawable); 322 | container.addView(image, layoutParams); 323 | } 324 | 325 | @Override 326 | public void applySelectState(View prev, View current, boolean reverse) { 327 | current.setSelected(true); 328 | current.requestLayout(); 329 | } 330 | 331 | private LinearLayout.LayoutParams generateLayoutParams(Drawable drawable, int size, int margin) { 332 | if (mLayoutParams == null) { 333 | final int minimumWidth = drawable.getMinimumWidth(); 334 | final int minimumHeight = drawable.getMinimumHeight(); 335 | LinearLayout.LayoutParams layoutParams; 336 | if (minimumWidth == 0 || minimumHeight == 0) { 337 | layoutParams = new LinearLayout.LayoutParams(size, size); 338 | } else { 339 | layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 340 | LinearLayout.LayoutParams.WRAP_CONTENT); 341 | } 342 | layoutParams.leftMargin = margin; 343 | mLayoutParams = layoutParams; 344 | } 345 | return mLayoutParams; 346 | } 347 | 348 | @Override 349 | public void applyUnSelectState(View indicator) { 350 | indicator.setSelected(false); 351 | indicator.requestLayout(); 352 | } 353 | 354 | @Override 355 | public boolean handleSpecial(LinearLayout container, int position) { 356 | return false; 357 | } 358 | ``` 359 | 360 | 除此之外,还有一个``JDIndicatorAdapter``,这里就不贴代码了,感兴趣的可以自己看看。 361 | 362 | 然后通过调用以下方法设置自己定义的指示器适配器即可,建议各种配置设置都放在``setAdapter``方法调用之前. 363 | 364 | ```java 365 | /** 366 | * 设置指示适配器 367 | * 368 | * @param indicatorAdapter IndicatorAdapter 369 | */ 370 | public void setIndicatorAdapter(IndicatorAdapter indicatorAdapter) { 371 | this.setIndicatorAdapter(indicatorAdapter, true); 372 | } 373 | ``` 374 | 375 | ### 3.页面切换效果 376 | 377 | 观察了市面上大多数知名app后,发现并没有使用多么炫酷的切换效果,都是一般的平滑过度,所以这里也没有内置切换效果,不过开放了接口,有需求的同学可以自己设置。 378 | 379 | 常见的切换效果参考[MagicViewPager](https://github.com/hongyangAndroid/MagicViewPager) 380 | 381 | ```java 382 | public void setPageTransformer(ViewPager.PageTransformer pageTransformer) 383 | ``` 384 | 385 | ### 4.CardView圆角和硬件加速 386 | 387 | 如果需要CardView``的圆角效果,就不要设置``lb_lrMargin``,否则你设置任何圆角效果都是毫无意义的,这关系到硬件加速,具体原因还不清楚。但是可以使用Glide的圆角转换功能设置圆角,具体如下: 388 | 389 | ```kotlin 390 | val itemView = holder.itemView as ImageView 391 | Glide.with(holder.context) 392 | .load(data) 393 | .apply( 394 | //实现图片圆角 395 | RequestOptions() 396 | .transforms( 397 | CenterCrop(), RoundedCorners(20) 398 | ) 399 | ) 400 | .into(itemView) 401 | ``` 402 | 403 | ### 5.设置页面切换时间来控制切换动画快慢 404 | 405 | ```java 406 | public void setTransformDuration(int duration) 407 | ``` 408 | 409 | ## 感谢 410 | 411 | [**BaseRecyclerViewAdapterHelper**](https://github.com/CymChad/BaseRecyclerViewAdapterHelper)(思想来源) 412 | 413 | [**glide**](https://github.com/bumptech/glide)(内置图片加载框架) 414 | 415 | [**wanandroid**](http://www.wanandroid.com/)(素材来源) 416 | 417 | [**MagicViewPager**](https://github.com/hongyangAndroid/MagicViewPager)(页面切换效果参考) 418 | 419 | ## 联系我 420 | 421 | QQ群 422 | 423 | ![qq交流群](https://github.com/wenjiangit/LoopBanner/blob/master/resource/qq_group.jpg) 424 | 425 | 邮箱:824636515@qq.com 426 | 427 | 428 | -------------------------------------------------------------------------------- /loopbanner/src/main/java/com/wenjian/loopbanner/LoopBanner.java: -------------------------------------------------------------------------------- 1 | package com.wenjian.loopbanner; 2 | 3 | import android.annotation.TargetApi; 4 | import android.arch.lifecycle.GenericLifecycleObserver; 5 | import android.arch.lifecycle.Lifecycle; 6 | import android.arch.lifecycle.LifecycleOwner; 7 | import android.content.Context; 8 | import android.content.res.TypedArray; 9 | import android.graphics.drawable.Drawable; 10 | import android.graphics.drawable.StateListDrawable; 11 | import android.os.Build; 12 | import android.os.Handler; 13 | import android.support.annotation.DrawableRes; 14 | import android.support.annotation.FloatRange; 15 | import android.support.annotation.NonNull; 16 | import android.support.annotation.Nullable; 17 | import android.support.v4.content.ContextCompat; 18 | import android.support.v4.view.ViewPager; 19 | import android.support.v7.widget.LinearLayoutManager; 20 | import android.support.v7.widget.PagerSnapHelper; 21 | import android.support.v7.widget.RecyclerView; 22 | import android.util.AttributeSet; 23 | import android.util.Log; 24 | import android.view.Gravity; 25 | import android.view.View; 26 | import android.view.ViewTreeObserver; 27 | import android.widget.FrameLayout; 28 | import android.widget.LinearLayout; 29 | 30 | import com.wenjian.loopbanner.indicator.IndicatorAdapter; 31 | import com.wenjian.loopbanner.indicator.JDIndicatorAdapter; 32 | import com.wenjian.loopbanner.indicator.SelectDrawableAdapter; 33 | import com.wenjian.loopbanner.transformer.ScalePageTransformer; 34 | 35 | import java.util.List; 36 | 37 | import static android.support.v7.widget.RecyclerView.SCROLL_STATE_DRAGGING; 38 | import static android.support.v7.widget.RecyclerView.SCROLL_STATE_IDLE; 39 | 40 | 41 | /** 42 | * Description: LoopBanner 43 | * Date: 2018/12/4 44 | * 45 | * @author jian.wen@ubtrobot.com 46 | */ 47 | public class LoopBanner extends FrameLayout { 48 | 49 | private static final int GRAVITY_BOTTOM_LEFT = 1; 50 | private static final int GRAVITY_BOTTOM_RIGHT = 2; 51 | private static final int GRAVITY_BOTTOM_CENTER = 3; 52 | private static final int DEFAULT_GRAVITY = GRAVITY_BOTTOM_CENTER; 53 | private static final long DEFAULT_INTERVAL_TIME = 3000L; 54 | private static final int DEFAULT_PAGE_LIMIT = 2; 55 | private static final int DEFAULT_INDICATOR_SIZE = 6; 56 | private static final int DEFAULT_INDICATOR_MARGIN = 3; 57 | private static final int DEFAULT_INDICATOR_MARGIN_TO_PARENT = 16; 58 | private static final String TAG = "LoopBanner"; 59 | 60 | /** 61 | * page切换周期 62 | */ 63 | private long mInterval; 64 | 65 | /** 66 | * page对于父布局的上边距 67 | */ 68 | private int mTopMargin; 69 | 70 | /** 71 | * page对于父布局的下边距 72 | */ 73 | private int mBottomMargin; 74 | 75 | /** 76 | * page相对于父布局的左右边距 77 | */ 78 | private int mLrMargin; 79 | private RecyclerView mRecycler; 80 | /** 81 | * 离屏缓存page个数,和ViewPager的参数保持一致 82 | */ 83 | private int mOffscreenPageLimit; 84 | /** 85 | * 每个page之间的间距 86 | */ 87 | private int mPageMargin; 88 | /** 89 | * 当前选中位置 90 | */ 91 | private int mCurrentIndex = -1; 92 | private final Handler mHandler = new Handler(); 93 | /** 94 | * 循环滚动 95 | */ 96 | private final Runnable mLoopRunnable = new Runnable() { 97 | @Override 98 | public void run() { 99 | if (mAutoLoop) { 100 | int curPosition = findCurPosition(); 101 | if (curPosition == mCurrentIndex) { 102 | mRecycler.smoothScrollToPosition(++mCurrentIndex); 103 | } else { 104 | mRecycler.scrollToPosition(++mCurrentIndex); 105 | } 106 | mHandler.postDelayed(this, mInterval); 107 | } else { 108 | mHandler.removeCallbacks(this); 109 | } 110 | // Tools.logI(TAG, "setCurrentItem " + mCurrentIndex); 111 | } 112 | }; 113 | /** 114 | * 是否循环播放 115 | */ 116 | private boolean mCanLoop = true; 117 | /** 118 | * 所有缩放 119 | */ 120 | private float mLrScale; 121 | 122 | private LayoutParams mParams; 123 | /** 124 | * 是否处于循环播放中 125 | */ 126 | private boolean inLoop = false; 127 | /** 128 | * 指示器容器 129 | */ 130 | private LinearLayout mIndicatorContainer; 131 | /** 132 | * 单个指示器的大小 133 | */ 134 | private int mIndicatorSize; 135 | /** 136 | * 指示器间距 137 | */ 138 | private int mIndicatorMargin; 139 | /** 140 | * 指示器适配 141 | */ 142 | private IndicatorAdapter mIndicatorAdapter = new SelectDrawableAdapter(); 143 | 144 | /** 145 | * 指示器的位置 146 | */ 147 | private int mIndicatorGravity; 148 | /** 149 | * 是否显示指示器 150 | */ 151 | private boolean mShowIndicator; 152 | /** 153 | * 选中监听 154 | */ 155 | private OnPageSelectListener mSelectListener; 156 | /** 157 | * Indicator选中的资源 158 | */ 159 | private Drawable mSelectDrawable; 160 | /** 161 | * Indicator未选中的资源 162 | */ 163 | private Drawable mUnSelectDrawable; 164 | /** 165 | * 数据观察者 166 | */ 167 | private final RecyclerView.AdapterDataObserver mDataSetObserver = new RecyclerView.AdapterDataObserver() { 168 | @Override 169 | public void onChanged() { 170 | Tools.logI(TAG, "onChanged"); 171 | restoreInitState(); 172 | } 173 | 174 | @Override 175 | public void onItemRangeChanged(int positionStart, int itemCount) { 176 | super.onItemRangeChanged(positionStart, itemCount); 177 | Log.d(TAG, "onItemRangeChanged: "); 178 | } 179 | }; 180 | /** 181 | * mIndicatorContainer相对于父容器的垂直方向间距 182 | */ 183 | private int mIndicatorParentMarginV; 184 | /** 185 | * mIndicatorContainer相对于父容器的水平方向间距 186 | */ 187 | private int mIndicatorParentMarginH; 188 | private LinearLayoutManager mLayoutManager; 189 | private boolean mAutoLoop = true; 190 | private PagerSnapHelper mSnapHelper; 191 | 192 | public LoopBanner(@NonNull Context context) { 193 | this(context, null); 194 | } 195 | 196 | public LoopBanner(@NonNull Context context, @Nullable AttributeSet attrs) { 197 | this(context, attrs, 0); 198 | } 199 | 200 | public LoopBanner(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 201 | super(context, attrs, defStyleAttr); 202 | initAttr(context, attrs, defStyleAttr, 0); 203 | } 204 | 205 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 206 | public LoopBanner(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 207 | super(context, attrs, defStyleAttr, defStyleRes); 208 | initAttr(context, attrs, defStyleAttr, defStyleRes); 209 | } 210 | 211 | private void initAttr(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 212 | TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LoopBanner, defStyleAttr, defStyleRes); 213 | mCanLoop = a.getBoolean(R.styleable.LoopBanner_lb_canLoop, true); 214 | mShowIndicator = a.getBoolean(R.styleable.LoopBanner_lb_showIndicator, true); 215 | mInterval = a.getInteger(R.styleable.LoopBanner_lb_interval, (int) DEFAULT_INTERVAL_TIME); 216 | mOffscreenPageLimit = a.getInteger(R.styleable.LoopBanner_lb_offsetPageLimit, DEFAULT_PAGE_LIMIT); 217 | mPageMargin = (int) a.getDimension(R.styleable.LoopBanner_lb_pageMargin, 0); 218 | final int margin = (int) a.getDimension(R.styleable.LoopBanner_lb_margin, 0); 219 | mLrMargin = (int) a.getDimension(R.styleable.LoopBanner_lb_lrMargin, margin); 220 | mTopMargin = (int) a.getDimension(R.styleable.LoopBanner_lb_topMargin, margin); 221 | mBottomMargin = (int) a.getDimension(R.styleable.LoopBanner_lb_bottomMargin, margin); 222 | mLrScale = a.getFloat(R.styleable.LoopBanner_lb_lrScale, 0f); 223 | //for indicator 224 | mIndicatorGravity = a.getInt(R.styleable.LoopBanner_lb_indicatorGravity, DEFAULT_GRAVITY); 225 | mIndicatorSize = (int) a.getDimension(R.styleable.LoopBanner_lb_indicatorSize, Tools.dp2px(context, DEFAULT_INDICATOR_SIZE)); 226 | mIndicatorMargin = (int) a.getDimension(R.styleable.LoopBanner_lb_indicatorMargin, Tools.dp2px(context, DEFAULT_INDICATOR_MARGIN)); 227 | mIndicatorParentMarginV = (int) a.getDimension(R.styleable.LoopBanner_lb_indicatorParentMarginV, Tools.dp2px(context, DEFAULT_INDICATOR_MARGIN_TO_PARENT)); 228 | mIndicatorParentMarginH = (int) a.getDimension(R.styleable.LoopBanner_lb_indicatorParentMarginH, Tools.dp2px(context, DEFAULT_INDICATOR_MARGIN_TO_PARENT)); 229 | mSelectDrawable = a.getDrawable(R.styleable.LoopBanner_lb_indicatorSelect); 230 | mUnSelectDrawable = a.getDrawable(R.styleable.LoopBanner_lb_indicatorUnSelect); 231 | int style = a.getInt(R.styleable.LoopBanner_lb_indicatorStyle, 0); 232 | handleIndicatorStyle(style); 233 | a.recycle(); 234 | init(); 235 | } 236 | 237 | private void handleIndicatorStyle(int style) { 238 | Style s; 239 | switch (style) { 240 | case 1: 241 | s = Style.JD; 242 | break; 243 | case 2: 244 | s = Style.PILL; 245 | break; 246 | default: 247 | s = Style.NORMAL; 248 | } 249 | setIndicatorStyle(s, false); 250 | } 251 | 252 | 253 | /** 254 | * 恢复初始状态 255 | */ 256 | private void restoreInitState() { 257 | createIndicatorIfNeed(); 258 | startInternal(true); 259 | } 260 | 261 | 262 | private void setProperIndex(int dataSize, int curIndex) { 263 | Tools.logI(TAG, "oldIndex: " + curIndex); 264 | int ret = Math.round(curIndex * 1.0f / dataSize + 0.5f) * dataSize; 265 | mCurrentIndex = ret >= 0 ? ret : 0; 266 | Tools.logI(TAG, "mCurrentIndex: " + mCurrentIndex); 267 | } 268 | 269 | private void init() { 270 | 271 | mRecycler = new RecyclerView(getContext()); 272 | setupViewPager(mRecycler); 273 | 274 | mParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); 275 | this.addView(mRecycler, mParams); 276 | 277 | if (mShowIndicator) { 278 | initIndicatorContainer(); 279 | } 280 | } 281 | 282 | private void initIndicatorContainer() { 283 | mIndicatorContainer = new LinearLayout(getContext()); 284 | mIndicatorContainer.setOrientation(LinearLayout.HORIZONTAL); 285 | LayoutParams layoutParams = createLayoutParams(); 286 | this.addView(mIndicatorContainer, layoutParams); 287 | } 288 | 289 | public LayoutParams createLayoutParams() { 290 | LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 291 | layoutParams.bottomMargin = mIndicatorParentMarginV; 292 | switch (mIndicatorGravity) { 293 | case GRAVITY_BOTTOM_LEFT: 294 | layoutParams.gravity = Gravity.BOTTOM | Gravity.START; 295 | layoutParams.leftMargin = mIndicatorParentMarginH + mLrMargin; 296 | break; 297 | case GRAVITY_BOTTOM_RIGHT: 298 | layoutParams.gravity = Gravity.BOTTOM | Gravity.END; 299 | layoutParams.rightMargin = mIndicatorParentMarginH + mLrMargin; 300 | break; 301 | case GRAVITY_BOTTOM_CENTER: 302 | layoutParams.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL; 303 | break; 304 | default: 305 | } 306 | return layoutParams; 307 | } 308 | 309 | 310 | private int mLastPosition; 311 | 312 | private void setupViewPager(final RecyclerView viewPager) { 313 | 314 | mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false); 315 | viewPager.setLayoutManager(mLayoutManager); 316 | 317 | initFirstWidth(); 318 | 319 | mSnapHelper = new PagerSnapHelper(); 320 | mSnapHelper.attachToRecyclerView(viewPager); 321 | viewPager.addOnScrollListener(new RecyclerView.OnScrollListener() { 322 | @Override 323 | public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { 324 | super.onScrollStateChanged(recyclerView, newState); 325 | final int cur = findCurPosition(); 326 | if (cur != mLastPosition) { 327 | Tools.logI(TAG, "onPageSelected: " + cur); 328 | mCurrentIndex = cur; 329 | notifySelectChange(cur); 330 | updateIndicators(cur, mLastPosition); 331 | mLastPosition = cur; 332 | } 333 | switch (newState) { 334 | case SCROLL_STATE_DRAGGING: 335 | stopInternal(); 336 | break; 337 | case SCROLL_STATE_IDLE: 338 | startInternal(false); 339 | break; 340 | default: 341 | } 342 | } 343 | }); 344 | 345 | 346 | // if (mLrScale > 0 && mLrScale < 1) { 347 | // viewPager.setPageTransformer(false, new ScalePageTransformer(mLrScale)); 348 | // } 349 | } 350 | 351 | private int findCurPosition() { 352 | final View snapView = mSnapHelper.findSnapView(mLayoutManager); 353 | return mRecycler.getChildAdapterPosition(snapView); 354 | } 355 | 356 | private void initFirstWidth() { 357 | mRecycler.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 358 | @Override 359 | public void onGlobalLayout() { 360 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { 361 | mRecycler.getViewTreeObserver().removeOnGlobalLayoutListener(this); 362 | } else { 363 | mRecycler.getViewTreeObserver().removeGlobalOnLayoutListener(this); 364 | } 365 | seekToOriginPosition(); 366 | } 367 | }); 368 | } 369 | 370 | private void notifySelectChange(int position) { 371 | LoopAdapter adapter = getAdapter(); 372 | if (adapter == null || adapter.getDataSize() == 0) { 373 | return; 374 | } 375 | 376 | if (mSelectListener != null) { 377 | mSelectListener.onPageSelected(adapter.getDataPosition(position)); 378 | } 379 | } 380 | 381 | private void updateIndicators(int position, int lastPosition) { 382 | if (mIndicatorContainer == null) { 383 | return; 384 | } 385 | LoopAdapter adapter = getAdapter(); 386 | if (adapter == null || adapter.getDataSize() <= 1) { 387 | return; 388 | } 389 | 390 | final int dataPosition = adapter.getDataPosition(position); 391 | if (mIndicatorAdapter.handleSpecial(mIndicatorContainer, dataPosition)) { 392 | return; 393 | } 394 | final int childCount = mIndicatorContainer.getChildCount(); 395 | if (childCount > 0) { 396 | for (int i = 0; i < childCount; i++) { 397 | mIndicatorAdapter.applyUnSelectState(mIndicatorContainer.getChildAt(i)); 398 | } 399 | boolean auto = lastPosition == position; 400 | int prev; 401 | if (auto) { 402 | prev = computePrevPosition(adapter, lastPosition - 1); 403 | } else { 404 | prev = computePrevPosition(adapter, lastPosition); 405 | } 406 | 407 | mIndicatorAdapter.applySelectState(mIndicatorContainer.getChildAt(prev), 408 | mIndicatorContainer.getChildAt(dataPosition), lastPosition > position); 409 | } 410 | } 411 | 412 | private int computePrevPosition(LoopAdapter adapter, int lastPosition) { 413 | if (lastPosition >= 0) { 414 | return adapter.getDataPosition(lastPosition); 415 | } 416 | return adapter.getDataSize() - 1; 417 | } 418 | 419 | /** 420 | * 启动轮播 421 | * 422 | * @param force 强制启动 423 | */ 424 | @SuppressWarnings("ConstantConditions") 425 | private void startInternal(boolean force) { 426 | if (mCanLoop && force) { 427 | seekToOriginPosition(); 428 | } 429 | if (!mAutoLoop || !dataSizeValid()) { 430 | return; 431 | } 432 | if (inLoop) { 433 | return; 434 | } 435 | mHandler.removeCallbacks(mLoopRunnable); 436 | mHandler.postDelayed(mLoopRunnable, mInterval); 437 | inLoop = true; 438 | } 439 | 440 | private void seekToOriginPosition() { 441 | final LoopAdapter adapter = getAdapter(); 442 | if (adapter == null || adapter.getDataSize() == 0) { 443 | return; 444 | } 445 | //如果是刚开始自动轮播,先将页面定位到合适的位置 446 | setProperIndex(adapter.getDataSize(), 100); 447 | mLayoutManager.scrollToPositionWithOffset(mCurrentIndex, mLrMargin); 448 | Log.d(TAG, "seekToOriginPosition: " + mCurrentIndex); 449 | } 450 | 451 | 452 | /** 453 | * 保证数据的长度大于1才轮播 454 | */ 455 | private boolean dataSizeValid() { 456 | LoopAdapter adapter = getAdapter(); 457 | if (adapter == null) { 458 | return false; 459 | } 460 | return adapter.getDataSize() > 1; 461 | } 462 | 463 | private void stopInternal() { 464 | mHandler.removeCallbacks(mLoopRunnable); 465 | inLoop = false; 466 | } 467 | 468 | /** 469 | * 设置是否循环播放 470 | * 471 | * @param enable loop 472 | */ 473 | public void setCanLoop(boolean enable) { 474 | this.mCanLoop = enable; 475 | } 476 | 477 | 478 | /** 479 | * 是否自动轮播 480 | * 481 | * @param autoLoop 自动轮播 482 | */ 483 | public void setAutoLoop(boolean autoLoop) { 484 | this.mAutoLoop = autoLoop; 485 | } 486 | 487 | /** 488 | * 开启调试模式,可以输出日志信息 489 | */ 490 | public void openDebug() { 491 | Tools.setDebug(true); 492 | } 493 | 494 | /** 495 | * 设置上下左右与父布局的间距 496 | * 497 | * @param margin 间距 498 | */ 499 | public void setMargins(int margin) { 500 | checkAdapter("setMargins"); 501 | int marginDp = Tools.dp2px(getContext(), margin); 502 | mParams.setMargins(marginDp, marginDp, marginDp, marginDp); 503 | mLrMargin = mTopMargin = mBottomMargin = marginDp; 504 | mRecycler.setLayoutParams(mParams); 505 | adjustIndicator(); 506 | } 507 | 508 | /** 509 | * 设置page页与父布局的上边距 510 | * 511 | * @param topMargin 上边距 512 | */ 513 | public void setTopMargin(int topMargin) { 514 | checkAdapter("setTopMargin"); 515 | final int topMarginDp = Tools.dp2px(getContext(), topMargin); 516 | mParams.topMargin = topMarginDp; 517 | mTopMargin = topMarginDp; 518 | mRecycler.setLayoutParams(mParams); 519 | adjustIndicator(); 520 | } 521 | 522 | /** 523 | * 设置page页与父布局的下边距 524 | * 525 | * @param bottomMargin 下边距 526 | */ 527 | public void setBottomMargin(int bottomMargin) { 528 | checkAdapter("setBottomMargin"); 529 | mBottomMargin = Tools.dp2px(getContext(), bottomMargin); 530 | mParams.bottomMargin = mBottomMargin; 531 | mRecycler.setLayoutParams(mParams); 532 | adjustIndicator(); 533 | } 534 | 535 | /** 536 | * 设置中心page与父布局的左右边距 537 | * 538 | * @param lrMargin 左右边距 539 | */ 540 | public void setLrMargin(int lrMargin) { 541 | checkAdapter("setLrMargin"); 542 | mLrMargin = Tools.dp2px(getContext(), lrMargin); 543 | adjustIndicator(); 544 | } 545 | 546 | private void adjustIndicator() { 547 | if (mIndicatorContainer != null) { 548 | mIndicatorContainer.setLayoutParams(createLayoutParams()); 549 | } 550 | } 551 | 552 | public int getPageMargin() { 553 | return mPageMargin; 554 | } 555 | 556 | /** 557 | * 设置page与page之间的间距 558 | * 559 | * @param pageMargin page之间的间距 560 | */ 561 | public void setPageMargin(int pageMargin) { 562 | checkAdapter("setPageMargin"); 563 | mPageMargin = Tools.dp2px(getContext(), pageMargin); 564 | adjustIndicator(); 565 | } 566 | 567 | public int getOffscreenPageLimit() { 568 | return mOffscreenPageLimit; 569 | } 570 | 571 | /** 572 | * 设置离屏缓存个数,默认为2,即内存中同时存在5个页面 573 | * 574 | * @param limit 离屏缓存个数 575 | */ 576 | public void setOffscreenPageLimit(int limit) { 577 | mOffscreenPageLimit = limit; 578 | // mRecycler.setOffscreenPageLimit(limit); 579 | } 580 | 581 | public long getInterval() { 582 | return mInterval; 583 | } 584 | 585 | 586 | /** 587 | * 设置当前位置 588 | * 589 | * @param position 目标位置 590 | * @param smooth 是否缓慢移动 591 | */ 592 | public void setCurrentItem(int position, boolean smooth) { 593 | final LoopAdapter adapter = getAdapter(); 594 | if (adapter == null) { 595 | return; 596 | } 597 | final int dataPosition = adapter.getDataPosition(mCurrentIndex); 598 | int del = position - dataPosition; 599 | if (smooth) { 600 | mRecycler.smoothScrollToPosition(mCurrentIndex + del); 601 | } else { 602 | mRecycler.scrollToPosition(mCurrentIndex + del); 603 | } 604 | } 605 | 606 | 607 | /** 608 | * 设置当前位置 609 | * 610 | * @param position 目标位置 611 | */ 612 | public void setCurrentItem(int position) { 613 | setCurrentItem(position, false); 614 | } 615 | 616 | 617 | /** 618 | * 设置轮播间隔时间 619 | * 620 | * @param interval 间隔时间 621 | */ 622 | public void setInterval(long interval) { 623 | mInterval = interval; 624 | } 625 | 626 | /** 627 | * 设置page切换动画 628 | * 629 | * @param pageTransformer 切换动画 630 | */ 631 | public void setPageTransformer(ViewPager.PageTransformer pageTransformer) { 632 | // mRecycler.setPageTransformer(false, pageTransformer); 633 | } 634 | 635 | /** 636 | * 设置左右page的缩放比例 637 | * 638 | * @param scale 缩放比例(0-1) 639 | */ 640 | public void setLrScale(@FloatRange(from = 0, to = 1.0f) float scale) { 641 | this.setPageTransformer(new ScalePageTransformer(scale)); 642 | } 643 | 644 | /** 645 | * 开启缩放 646 | */ 647 | public void enableScale() { 648 | this.setPageTransformer(new ScalePageTransformer()); 649 | } 650 | 651 | @Override 652 | public void onWindowFocusChanged(boolean hasWindowFocus) { 653 | super.onWindowFocusChanged(hasWindowFocus); 654 | Tools.logI(TAG, "onWindowFocusChanged," + hasWindowFocus); 655 | } 656 | 657 | @Override 658 | protected void onWindowVisibilityChanged(int visibility) { 659 | super.onWindowVisibilityChanged(visibility); 660 | Tools.logI(TAG, "onWindowVisibilityChanged," + visibility); 661 | if (visibility == VISIBLE) { 662 | startInternal(false); 663 | } else { 664 | stopInternal(); 665 | } 666 | } 667 | 668 | /** 669 | * 强制停止轮播 670 | */ 671 | public void forceStop() { 672 | stopInternal(); 673 | mAutoLoop = false; 674 | } 675 | 676 | /** 677 | * 强制开始轮播,适配某些机型自动轮播失效的时候需要手动调用该函数 678 | */ 679 | public void forceStart() { 680 | startInternal(false); 681 | } 682 | 683 | private void createIndicatorIfNeed() { 684 | if (!mShowIndicator || !dataSizeValid()) { 685 | if (mIndicatorContainer != null) { 686 | this.removeView(mIndicatorContainer); 687 | mIndicatorContainer = null; 688 | } 689 | return; 690 | } 691 | //need show indicator 692 | if (mIndicatorContainer == null) { 693 | initIndicatorContainer(); 694 | } 695 | 696 | mIndicatorContainer.removeAllViews(); 697 | 698 | for (int i = 0; i < getAdapter().getDataSize(); i++) { 699 | mIndicatorAdapter.addIndicator(mIndicatorContainer, makeDrawable(), mIndicatorSize, mIndicatorMargin); 700 | } 701 | updateIndicators(0, -1); 702 | } 703 | 704 | private Drawable makeDrawable() { 705 | Drawable ret; 706 | if (mSelectDrawable != null && mUnSelectDrawable != null) { 707 | StateListDrawable listDrawable = new StateListDrawable(); 708 | listDrawable.addState(new int[]{android.R.attr.state_selected}, mSelectDrawable); 709 | listDrawable.addState(new int[]{}, mUnSelectDrawable); 710 | ret = listDrawable; 711 | } else { 712 | ret = ContextCompat.getDrawable(getContext(), R.drawable.indicator_color_selector); 713 | } 714 | return ret; 715 | } 716 | 717 | private void checkAdapter(String methodName) { 718 | LoopAdapter adapter = getAdapter(); 719 | if (adapter != null) { 720 | throw new IllegalStateException("please call " + methodName + " before setAdapter"); 721 | } 722 | } 723 | 724 | @Nullable 725 | public LoopAdapter getAdapter() { 726 | final RecyclerView.Adapter adapter = mRecycler.getAdapter(); 727 | return adapter == null ? null : (LoopAdapter) adapter; 728 | } 729 | 730 | /** 731 | * 设置Adapter加载数据 732 | * 733 | * @param adapter LoopAdapter 734 | */ 735 | public void setAdapter(LoopAdapter adapter) { 736 | Tools.checkNotNull(adapter); 737 | adapter.setCanLoop(mCanLoop); 738 | adapter.registerAdapterDataObserver(mDataSetObserver); 739 | adapter.setHelper(new AdapterHelper(mPageMargin, mLrMargin)); 740 | mRecycler.setAdapter(adapter); 741 | restoreInitState(); 742 | } 743 | 744 | /** 745 | * 直接设置图片地址和点击事件 746 | * 747 | * @param urls 图片地址 748 | */ 749 | public void setImages(List urls, OnPageClickListener listener) { 750 | SimpleImageAdapter imageAdapter = new SimpleImageAdapter(urls); 751 | imageAdapter.setOnPageClickListener(listener); 752 | this.setAdapter(imageAdapter); 753 | } 754 | 755 | public void setImages(List urls) { 756 | this.setImages(urls, null); 757 | } 758 | 759 | /** 760 | * 是否使用指示器 761 | * 762 | * @param enable 是否可用 763 | */ 764 | public void enableIndicator(boolean enable) { 765 | this.mShowIndicator = enable; 766 | if (enable) { 767 | if (mIndicatorContainer == null) { 768 | initIndicatorContainer(); 769 | } 770 | } else { 771 | if (mIndicatorContainer != null) { 772 | this.removeView(mIndicatorContainer); 773 | mIndicatorContainer = null; 774 | } 775 | } 776 | } 777 | 778 | private void setIndicatorAdapter(IndicatorAdapter indicatorAdapter, boolean byeUser) { 779 | if (byeUser) { 780 | checkAdapter("setIndicatorAdapter"); 781 | } 782 | mIndicatorAdapter = Tools.checkNotNull(indicatorAdapter, "indicatorAdapter is null"); 783 | } 784 | 785 | 786 | /** 787 | * 綁定當前Activity或Fragment的生命周期 788 | * 789 | * @param owner LifecycleOwner 790 | */ 791 | public void bindLifecycle(LifecycleOwner owner) { 792 | Tools.checkNotNull(owner); 793 | owner.getLifecycle().addObserver(new GenericLifecycleObserver() { 794 | @Override 795 | public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) { 796 | Tools.logI(TAG, "onStateChanged " + event); 797 | if (event.equals(Lifecycle.Event.ON_START)) { 798 | startInternal(false); 799 | } else if (event.equals(Lifecycle.Event.ON_STOP)) { 800 | stopInternal(); 801 | } 802 | } 803 | }); 804 | } 805 | 806 | 807 | /** 808 | * 设置指示适配器 809 | * 810 | * @param indicatorAdapter IndicatorAdapter 811 | */ 812 | public void setIndicatorAdapter(IndicatorAdapter indicatorAdapter) { 813 | this.setIndicatorAdapter(indicatorAdapter, true); 814 | } 815 | 816 | /** 817 | * 设置页面选中监听 818 | * 819 | * @param listener OnPageSelectListener 820 | */ 821 | public void setOnPageSelectListener(OnPageSelectListener listener) { 822 | this.mSelectListener = listener; 823 | } 824 | 825 | /** 826 | * 设置指示器资源 827 | * 828 | * @param selectRes 选中 829 | * @param unSelectRes 未选中 830 | */ 831 | public void setIndicatorResource(@DrawableRes int selectRes, @DrawableRes int unSelectRes) { 832 | this.setIndicatorResource(selectRes, unSelectRes, true); 833 | } 834 | 835 | private void setIndicatorResource(@DrawableRes int selectRes, @DrawableRes int unSelectRes, boolean byUser) { 836 | if (byUser) { 837 | checkAdapter("setIndicatorResource"); 838 | } 839 | Drawable selectDrawable = ContextCompat.getDrawable(getContext(), selectRes); 840 | Drawable unSelectDrawable = ContextCompat.getDrawable(getContext(), unSelectRes); 841 | this.mSelectDrawable = selectDrawable; 842 | this.mUnSelectDrawable = unSelectDrawable; 843 | } 844 | 845 | private void setIndicatorStyle(Style style, boolean byUser) { 846 | if (byUser) { 847 | checkAdapter("setIndicatorStyle"); 848 | } 849 | switch (style) { 850 | case JD: 851 | setIndicatorAdapter(new JDIndicatorAdapter(), byUser); 852 | break; 853 | case PILL: 854 | setIndicatorResource(R.drawable.indicator_select, R.drawable.indicator_unselect, byUser); 855 | break; 856 | case NORMAL: 857 | default: 858 | } 859 | } 860 | 861 | /** 862 | * 设置指示器风格 863 | * 864 | * @param style Style 865 | */ 866 | public void setIndicatorStyle(Style style) { 867 | this.setIndicatorStyle(style, true); 868 | } 869 | 870 | /** 871 | * 设置page切换时长 872 | * 873 | * @param duration 时长 874 | */ 875 | public void setTransformDuration(int duration) { 876 | if (duration < 0) { 877 | duration = 0; 878 | } 879 | LoopScroller scroller = new LoopScroller(getContext()); 880 | scroller.setScrollerDuration(duration); 881 | // scroller.linkViewPager(mRecycler); 882 | } 883 | 884 | public enum Style { 885 | /** 886 | * 京东 887 | */ 888 | JD, 889 | /** 890 | * 药丸 891 | */ 892 | PILL, 893 | /** 894 | * 普通 895 | */ 896 | NORMAL 897 | 898 | } 899 | 900 | public interface OnPageClickListener { 901 | /** 902 | * page点击事件处理 903 | * 904 | * @param itemView 被点击的view 905 | * @param position 位置 906 | */ 907 | void onPageClick(View itemView, int position); 908 | } 909 | 910 | /** 911 | * page选中监听 912 | */ 913 | public interface OnPageSelectListener { 914 | 915 | /** 916 | * page选中事件处理 917 | * 918 | * @param position 被选中的位置 919 | */ 920 | void onPageSelected(int position); 921 | } 922 | 923 | } 924 | --------------------------------------------------------------------------------