├── app ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ ├── colors.xml │ │ │ │ ├── dimens.xml │ │ │ │ └── styles.xml │ │ │ ├── mipmap-hdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-mdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxxhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── drawable │ │ │ │ ├── shape_point_unselect.xml │ │ │ │ └── shape_point_select.xml │ │ │ ├── values-w820dp │ │ │ │ └── dimens.xml │ │ │ └── layout │ │ │ │ └── activity_main.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── com │ │ │ └── donkingliang │ │ │ └── bannerdemo │ │ │ └── MainActivity.java │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── donkingliang │ │ │ └── bannerdemo │ │ │ └── ExampleUnitTest.java │ └── androidTest │ │ └── java │ │ └── com │ │ └── donkingliang │ │ └── bannerdemo │ │ └── ExampleInstrumentedTest.java ├── proguard-rules.pro └── build.gradle ├── banner ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ └── attr.xml │ │ │ └── drawable │ │ │ │ ├── text_indicator_bg.xml │ │ │ │ └── indicator_divider.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── com │ │ │ └── donkingliang │ │ │ └── banner │ │ │ ├── NumberIndicator.java │ │ │ ├── DensityUtils.java │ │ │ ├── ViewPagerScroller.java │ │ │ ├── BannerPagerAdapter.java │ │ │ └── CustomBanner.java │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── donkingliang │ │ │ └── banner │ │ │ └── ExampleUnitTest.java │ └── androidTest │ │ └── java │ │ └── com │ │ └── donkingliang │ │ └── banner │ │ └── ApplicationTest.java ├── proguard-rules.pro ├── build.gradle └── banner.iml ├── settings.gradle ├── 演示.gif ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew.bat ├── README.md └── gradlew /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /banner/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app',':banner' 2 | -------------------------------------------------------------------------------- /演示.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/donkingliang/CustomBanner/HEAD/演示.gif -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | BannerDemo 3 | 4 | -------------------------------------------------------------------------------- /banner/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | banner 3 | 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/donkingliang/CustomBanner/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/donkingliang/CustomBanner/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/donkingliang/CustomBanner/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/donkingliang/CustomBanner/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/donkingliang/CustomBanner/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/donkingliang/CustomBanner/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /banner/src/main/res/drawable/text_indicator_bg.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip 7 | -------------------------------------------------------------------------------- /banner/src/main/res/drawable/indicator_divider.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/shape_point_unselect.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 9 | -------------------------------------------------------------------------------- /banner/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/shape_point_select.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /banner/src/test/java/com/donkingliang/banner/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.donkingliang.banner; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * To work on unit tests, switch the Test Artifact in the Build Variants view. 9 | */ 10 | public class ExampleUnitTest { 11 | @Test 12 | public void addition_isCorrect() throws Exception { 13 | assertEquals(4, 2 + 2); 14 | } 15 | } -------------------------------------------------------------------------------- /banner/src/androidTest/java/com/donkingliang/banner/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.donkingliang.banner; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /app/src/test/java/com/donkingliang/bannerdemo/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.donkingliang.bannerdemo; 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() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in C:\Users\admin\AppData\Local\Android\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /banner/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in C:\Users\Administrator\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | -------------------------------------------------------------------------------- /banner/src/main/java/com/donkingliang/banner/NumberIndicator.java: -------------------------------------------------------------------------------- 1 | package com.donkingliang.banner; 2 | 3 | import android.content.Context; 4 | import android.graphics.Color; 5 | import android.widget.TextView; 6 | 7 | public class NumberIndicator extends TextView { 8 | 9 | public NumberIndicator(Context context) { 10 | super(context); 11 | setTextColor(Color.WHITE); 12 | setTextSize(14); 13 | setBackgroundResource(R.drawable.text_indicator_bg); 14 | int padding = DensityUtils.dp2px(context, 5); 15 | setPadding(padding,padding,padding,padding); 16 | } 17 | 18 | @Override 19 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 20 | //保证TextIndicator的宽高一致(正方形) 21 | super.onMeasure(widthMeasureSpec, widthMeasureSpec); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /banner/src/main/res/values/attr.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/donkingliang/bannerdemo/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.donkingliang.bannerdemo; 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 | * Instrumentation 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() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.donkingliang.bannerdemo", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion "25.0.3" 6 | defaultConfig { 7 | applicationId "com.donkingliang.bannerdemo" 8 | minSdkVersion 11 9 | targetSdkVersion 25 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(dir: 'libs', include: ['*.jar']) 24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 25 | exclude group: 'com.android.support', module: 'support-annotations' 26 | }) 27 | compile 'com.android.support:appcompat-v7:25.3.1' 28 | testCompile 'junit:junit:4.12' 29 | 30 | compile 'com.github.bumptech.glide:glide:3.7.0' 31 | 32 | compile project(":banner") 33 | } 34 | -------------------------------------------------------------------------------- /banner/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion "25.0.3" 6 | 7 | defaultConfig { 8 | minSdkVersion 11 9 | targetSdkVersion 25 10 | versionCode 2 11 | versionName "1.1.0" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | } 20 | 21 | dependencies { 22 | compile fileTree(dir: 'libs', include: ['*.jar']) 23 | testCompile 'junit:junit:4.12' 24 | compile 'com.android.support:appcompat-v7:25.3.1' 25 | } 26 | 27 | //--------------------------------------------- 28 | 29 | // 指定编码 30 | tasks.withType(JavaCompile) { 31 | options.encoding = "UTF-8" 32 | } 33 | 34 | // 打包源码 35 | task sourcesJar(type: Jar) { 36 | from android.sourceSets.main.java.srcDirs 37 | classifier = 'sources' 38 | } 39 | 40 | task javadoc(type: Javadoc) { 41 | failOnError false 42 | source = android.sourceSets.main.java.sourceFiles 43 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 44 | classpath += configurations.compile 45 | } 46 | 47 | artifacts { 48 | archives sourcesJar 49 | } -------------------------------------------------------------------------------- /banner/src/main/java/com/donkingliang/banner/DensityUtils.java: -------------------------------------------------------------------------------- 1 | package com.donkingliang.banner; 2 | 3 | import android.content.Context; 4 | import android.util.TypedValue; 5 | 6 | public class DensityUtils { 7 | 8 | private DensityUtils() { 9 | /* cannot be instantiated */ 10 | throw new UnsupportedOperationException("cannot be instantiated"); 11 | } 12 | 13 | /** 14 | * dp转px 15 | */ 16 | public static int dp2px(Context context, float dpVal) { 17 | return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 18 | dpVal, context.getResources().getDisplayMetrics()); 19 | } 20 | 21 | /** 22 | * sp转px 23 | */ 24 | public static int sp2px(Context context, float spVal) { 25 | return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 26 | spVal, context.getResources().getDisplayMetrics()); 27 | } 28 | 29 | /** 30 | * px转dp 31 | */ 32 | public static float px2dp(Context context, float pxVal) { 33 | final float scale = context.getResources().getDisplayMetrics().density; 34 | return (pxVal / scale); 35 | } 36 | 37 | /** 38 | * px转sp 39 | */ 40 | public static float px2sp(Context context, float pxVal) { 41 | return (pxVal / context.getResources().getDisplayMetrics().scaledDensity); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /banner/src/main/java/com/donkingliang/banner/ViewPagerScroller.java: -------------------------------------------------------------------------------- 1 | package com.donkingliang.banner; 2 | 3 | import android.content.Context; 4 | import android.view.animation.Interpolator; 5 | import android.widget.Scroller; 6 | 7 | public class ViewPagerScroller extends Scroller { 8 | 9 | private int mScrollDuration = 360; 10 | private boolean sudden; 11 | 12 | public ViewPagerScroller(Context context) { 13 | super(context); 14 | } 15 | 16 | public ViewPagerScroller(Context context, Interpolator interpolator) { 17 | super(context, interpolator); 18 | } 19 | 20 | public ViewPagerScroller(Context context, Interpolator interpolator, 21 | boolean flywheel) { 22 | super(context, interpolator, flywheel); 23 | } 24 | 25 | @Override 26 | public void startScroll(int startX, int startY, int dx, int dy, int duration) { 27 | super.startScroll(startX, startY, dx, dy, sudden ? 0 : mScrollDuration); 28 | } 29 | 30 | @Override 31 | public void startScroll(int startX, int startY, int dx, int dy) { 32 | super.startScroll(startX, startY, dx, dy, sudden ? 0 : mScrollDuration); 33 | } 34 | 35 | public int getScrollDuration() { 36 | return mScrollDuration; 37 | } 38 | 39 | public void setScrollDuration(int scrollDuration) { 40 | this.mScrollDuration = scrollDuration; 41 | } 42 | 43 | public boolean isSudden() { 44 | return sudden; 45 | } 46 | 47 | public void setSudden(boolean zero) { 48 | this.sudden = zero; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /banner/src/main/java/com/donkingliang/banner/BannerPagerAdapter.java: -------------------------------------------------------------------------------- 1 | package com.donkingliang.banner; 2 | 3 | import android.content.Context; 4 | import android.support.v4.view.PagerAdapter; 5 | import android.util.SparseArray; 6 | import android.view.View; 7 | import android.view.ViewGroup; 8 | import android.view.ViewParent; 9 | 10 | import java.util.List; 11 | 12 | public class BannerPagerAdapter extends PagerAdapter { 13 | 14 | private Context mContext; 15 | private List mData; 16 | private CustomBanner.ViewCreator mCreator; 17 | private CustomBanner.OnPageClickListener mOnPageClickListener; 18 | 19 | private SparseArray views = new SparseArray<>(); 20 | 21 | public BannerPagerAdapter(Context context, CustomBanner.ViewCreator creator, List data) { 22 | mContext = context; 23 | mCreator = creator; 24 | mData = data; 25 | } 26 | 27 | @Override 28 | public int getCount() { 29 | return mData == null || mData.isEmpty() ? 0 : mData.size() + 2; 30 | } 31 | 32 | @Override 33 | public boolean isViewFromObject(View arg0, Object arg1) { 34 | return arg0 == arg1; 35 | } 36 | 37 | @Override 38 | public void destroyItem(ViewGroup container, int position, 39 | Object object) { 40 | //Warning:不要在这里调用removeView 41 | } 42 | 43 | @Override 44 | public Object instantiateItem(ViewGroup container, final int position) { 45 | 46 | final int item = getActualPosition(position); 47 | 48 | View view = views.get(position); 49 | 50 | if (view == null) { 51 | view = mCreator.createView(mContext, item); 52 | views.put(position, view); 53 | } 54 | 55 | //如果View已经在之前添加到了一个父组件,则必须先remove,否则会抛出IllegalStateException。 56 | ViewParent vp = view.getParent(); 57 | if (vp != null) { 58 | ViewGroup parent = (ViewGroup) vp; 59 | parent.removeView(view); 60 | } 61 | 62 | final T t = mData.get(item); 63 | 64 | mCreator.updateUI(mContext, view, item, t); 65 | 66 | view.setOnClickListener(new View.OnClickListener() { 67 | @Override 68 | public void onClick(View v) { 69 | if (mOnPageClickListener != null) { 70 | mOnPageClickListener.onPageClick(item, t); 71 | } 72 | } 73 | }); 74 | 75 | container.addView(view); 76 | return view; 77 | } 78 | 79 | private int getActualPosition(int position) { 80 | if (position == 0) { 81 | return mData.size() - 1; 82 | } else if (position == getCount() - 1) { 83 | return 0; 84 | } else { 85 | return position - 1; 86 | } 87 | } 88 | 89 | public void setOnPageClickListener(CustomBanner.OnPageClickListener l) { 90 | mOnPageClickListener = l; 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CustomBanner 2 | Android轮播图控件,支持任何View的轮播,而不仅仅是图片(ImageView),完全自定义的轮播指示器和轮播图样式,使用非常简单。下面是CustomBanner具体使用讲解: 3 | ### 1、引入依赖 4 | 在Project的build.gradle在添加以下代码 5 | ``` 6 | allprojects { 7 | repositories { 8 | ... 9 | maven { url 'https://jitpack.io' } 10 | } 11 | } 12 | ``` 13 | 在Module的build.gradle在添加以下代码 14 | ``` 15 | dependencies { 16 | compile 'com.github.donkingliang:CustomBanner:1.1.3' 17 | } 18 | ``` 19 | ### 2、编写布局 20 | ```xml 21 | 22 | //指示器的点的间隔 32 | 33 | 34 | 35 | //指示器的位置 有左。中、右三个值 42 | 43 | 44 | 45 | //指示器类型 没有指示器 51 | ``` 52 | ### 3、CustomBanner的方法使用 53 | #### 1)、设置数据 54 | ```java 55 | mBanner.setPages(new CustomBanner.ViewCreator() { 56 | @Override 57 | public View createView(Context context, int position) { 58 | //这里返回的是轮播图的项的布局 支持任何的布局 59 | //position 轮播图的第几个项 60 | ImageView imageView = new ImageView(context); 61 | return imageView; 62 | } 63 | 64 | @Override 65 | public void updateUI(Context context, View view, int position, String data) { 66 | //在这里更新轮播图的UI 67 | //position 轮播图的第几个项 68 | //view 轮播图当前项的布局 它是createView方法的返回值 69 | //data 轮播图当前项对应的数据 70 | Glide.with(context).load(data).into((ImageView) view); 71 | } 72 | }, beans); 73 | ``` 74 | 轮播图的布局支持任何的布局,轮播图的数据类型也是支持任何的数据类型,这里只是用ImageView和String举例而已。 75 | #### 2)、其他方法的使用 76 | ```java 77 | //设置指示器类型,有普通指示器(ORDINARY)、数字指示器(NUMBER)和没有指示器(NONE)三种类型。 78 | //这个方法跟在布局中设置app:indicatorStyle是一样的 79 | mBanner.setIndicatorStyle(CustomBanner.IndicatorStyle.ORDINARY); 80 | 81 | //设置两个点图片作为翻页指示器,只有指示器为普通指示器(ORDINARY)时有用。 82 | //这个方法跟在布局中设置app:indicatorSelectRes、app:indicatorUnSelectRes是一样的。 83 | //第一个参数是指示器的选中的样式,第二个参数是指示器的未选中的样式。 84 | mBanner.setIndicatorRes(R.drawable.shape_point_select,R.drawable.shape_point_unselect); 85 | mBanner.setIndicator(Drawable select, Drawable unSelect); 86 | 87 | //设置指示器的指示点间隔,只有指示器为普通指示器(ORDINARY)时有用。 88 | //这个方法跟在布局中设置app:indicatorInterval是一样的。 89 | mBanner.setIndicatorInterval(20) 90 | 91 | //设置指示器的方向。 92 | //这个方法跟在布局中设置app:indicatorGravity是一样的。 93 | mBanner.setIndicatorGravity(CustomBanner.IndicatorGravity.CENTER) 94 | 95 | //设置轮播图自动滚动轮播,参数是轮播图滚动的间隔时间 96 | //轮播图默认是不自动滚动的,如果不调用这个方法,轮播图将不会自动滚动。 97 | mBanner.startTurning(3600); 98 | 99 | //停止轮播图的自动滚动 100 | mBanner.stopTurning(); 101 | 102 | //设置轮播图的滚动速度 103 | mBanner.setScrollDuration(500); 104 | 105 | //设置轮播图的点击事件 106 | mBanner.setOnPageClickListener(new CustomBanner.OnPageClickListener() { 107 | @Override 108 | public void onPageClick(int position, String str) { 109 | //position 轮播图的第几个项 110 | //str 轮播图当前项对应的数据 111 | } 112 | }); 113 | ``` 114 | 以上是CustomBanner的主要常用方法,更多方法请查看源码。 115 | #### 3)、CustomBanner的很多方法都支持方法连缀,比如以下的方法可以这样调用。 116 | ```java 117 | mBanner.setPages(参数, 参数).setIndicatorRes(参数, 参数).setIndicatorGravity(参数).startTurning(参数); 118 | ``` 119 | ### 效果图 120 | ![](https://github.com/donkingliang/CustomBanner/blob/master/%E6%BC%94%E7%A4%BA.gif) 121 | 122 | 在我的博客中对该轮播图控件的实现和核心代码有详细的分析讲解,欢迎大家访问[我的博客](http://blog.csdn.net/u010177022) 123 | [Android轮播图控件的实现详解](http://blog.csdn.net/u010177022/article/details/61931488) 124 | -------------------------------------------------------------------------------- /app/src/main/java/com/donkingliang/bannerdemo/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.donkingliang.bannerdemo; 2 | 3 | import android.content.Context; 4 | import android.os.Bundle; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.view.View; 7 | import android.widget.ImageView; 8 | 9 | import com.bumptech.glide.Glide; 10 | import com.donkingliang.banner.CustomBanner; 11 | 12 | import java.util.ArrayList; 13 | 14 | public class MainActivity extends AppCompatActivity { 15 | 16 | private CustomBanner mBanner; 17 | 18 | @Override 19 | protected void onCreate(Bundle savedInstanceState) { 20 | super.onCreate(savedInstanceState); 21 | setContentView(R.layout.activity_main); 22 | 23 | mBanner = (CustomBanner) findViewById(R.id.banner); 24 | 25 | ArrayList images = new ArrayList<>(); 26 | images.add("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3778456200,3076998411&fm=23&gp=0.jpg"); 27 | images.add("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3535338527,4000198595&fm=23&gp=0.jpg"); 28 | images.add("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1017904219,2460650030&fm=23&gp=0.jpg"); 29 | images.add("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2863927798,667335035&fm=23&gp=0.jpg"); 30 | images.add("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3885596348,1190704919&fm=23&gp=0.jpg"); 31 | images.add("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1597254274,1405139366&fm=23&gp=0.jpg"); 32 | images.add("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3513269361,2662598514&fm=23&gp=0.jpg"); 33 | 34 | setBean(images); 35 | } 36 | 37 | //设置普通指示器 38 | private void setBean(final ArrayList beans) { 39 | mBanner.setPages(new CustomBanner.ViewCreator() { 40 | @Override 41 | public View createView(Context context, int position) { 42 | ImageView imageView = new ImageView(context); 43 | imageView.setScaleType(ImageView.ScaleType.FIT_XY); 44 | return imageView; 45 | } 46 | 47 | @Override 48 | public void updateUI(Context context, View view, int position, String entity) { 49 | Glide.with(context).load(entity).into((ImageView) view); 50 | } 51 | }, beans) 52 | // //设置指示器为普通指示器 53 | // .setIndicatorStyle(CustomBanner.IndicatorStyle.ORDINARY) 54 | // //设置两个点图片作为翻页指示器,不设置则没有指示器,可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设 55 | // .setIndicatorRes(R.drawable.shape_point_select, R.drawable.shape_point_unselect) 56 | // //设置指示器的方向 57 | // .setIndicatorGravity(CustomBanner.IndicatorGravity.CENTER) 58 | // //设置指示器的指示点间隔 59 | // .setIndicatorInterval(20) 60 | //设置自动翻页 61 | .startTurning(5000); 62 | } 63 | 64 | // //设置普通指示器 65 | // private void setBean(final ArrayList beans) { 66 | // mBanner.setPages(new CustomBanner.ViewCreator() { 67 | // @Override 68 | // public View createView(Context context, int position) { 69 | // ImageView imageView = new ImageView(context); 70 | // imageView.setScaleType(ImageView.ScaleType.FIT_XY); 71 | // return imageView; 72 | // } 73 | // 74 | // @Override 75 | // public void updateUI(Context context, View view, int position, String entity) { 76 | // Glide.with(context).load(entity).into((ImageView) view); 77 | // } 78 | // }, beans) 79 | // //设置指示器为普通指示器 80 | // .setIndicatorStyle(CustomBanner.IndicatorStyle.NUMBER) 81 | // //设置指示器的方向 82 | // .setIndicatorGravity(CustomBanner.IndicatorGravity.RIGHT) 83 | // //设置自动翻页 84 | // .startTurning(5000); 85 | // } 86 | 87 | // //设置没有指示器 88 | // private void setBean(final ArrayList beans) { 89 | // mBanner.setPages(new CustomBanner.ViewCreator() { 90 | // @Override 91 | // public View createView(Context context, int position) { 92 | // ImageView imageView = new ImageView(context); 93 | // imageView.setScaleType(ImageView.ScaleType.FIT_XY); 94 | // return imageView; 95 | // } 96 | // 97 | // @Override 98 | // public void updateUI(Context context, View view, int position, String entity) { 99 | // Glide.with(context).load(entity).into((ImageView) view); 100 | // } 101 | // }, beans) 102 | // //设置没有指示器 103 | // .setIndicatorStyle(CustomBanner.IndicatorStyle.NONE) 104 | // //设置自动翻页 105 | // .startTurning(5000); 106 | // } 107 | } 108 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /banner/banner.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 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 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /banner/src/main/java/com/donkingliang/banner/CustomBanner.java: -------------------------------------------------------------------------------- 1 | package com.donkingliang.banner; 2 | 3 | import android.content.Context; 4 | import android.content.res.TypedArray; 5 | import android.graphics.Color; 6 | import android.graphics.drawable.Drawable; 7 | import android.graphics.drawable.ShapeDrawable; 8 | import android.os.Handler; 9 | import android.support.v4.view.ViewPager; 10 | import android.util.AttributeSet; 11 | import android.view.Gravity; 12 | import android.view.View; 13 | import android.view.ViewGroup; 14 | import android.view.animation.AccelerateInterpolator; 15 | import android.widget.FrameLayout; 16 | import android.widget.ImageView; 17 | import android.widget.LinearLayout; 18 | 19 | import java.lang.reflect.Field; 20 | import java.util.List; 21 | 22 | public class CustomBanner extends FrameLayout { 23 | 24 | private Context mContext; 25 | 26 | private ViewPager mBannerViewPager; 27 | //普通指示器的容器 28 | private LinearLayout mIndicatorLayout; 29 | //数字指示器 30 | private NumberIndicator mNumberIndicator; 31 | private BannerPagerAdapter mAdapter; 32 | private ViewPagerScroller mScroller; 33 | private long mIntervalTime; 34 | 35 | private Drawable mIndicatorSelectDrawable; 36 | private Drawable mIndicatorUnSelectDrawable; 37 | private int mIndicatorInterval; 38 | private IndicatorGravity mIndicatorGravity = IndicatorGravity.CENTER; 39 | private IndicatorStyle mIndicatorStyle = IndicatorStyle.ORDINARY; 40 | 41 | private int mBannerCount; 42 | private boolean isTurning; 43 | 44 | private OnPageClickListener mOnPageClickListener; 45 | private ViewPager.OnPageChangeListener mOnPageChangeListener; 46 | 47 | private Handler mTimeHandler = new Handler(); 48 | private Runnable mTurningTask = new Runnable() { 49 | @Override 50 | public void run() { 51 | if (isTurning && mBannerViewPager != null) { 52 | int page = mBannerViewPager.getCurrentItem() + 1; 53 | mBannerViewPager.setCurrentItem(page); 54 | mTimeHandler.postDelayed(mTurningTask, mIntervalTime); 55 | } 56 | } 57 | }; 58 | 59 | /** 60 | * 指示器方向 61 | */ 62 | public enum IndicatorGravity { 63 | LEFT, RIGHT, CENTER 64 | } 65 | 66 | /** 67 | * 指示器类型 68 | */ 69 | public enum IndicatorStyle { 70 | //没有指示器 71 | NONE, 72 | //数字指示器 73 | NUMBER, 74 | //普通指示器 75 | ORDINARY 76 | } 77 | 78 | public CustomBanner(Context context) { 79 | super(context); 80 | init(context); 81 | } 82 | 83 | public CustomBanner(Context context, AttributeSet attrs) { 84 | super(context, attrs); 85 | getAttrs(context, attrs); 86 | init(context); 87 | } 88 | 89 | public CustomBanner(Context context, AttributeSet attrs, int defStyleAttr) { 90 | super(context, attrs, defStyleAttr); 91 | getAttrs(context, attrs); 92 | init(context); 93 | } 94 | 95 | private void getAttrs(Context context, AttributeSet attrs) { 96 | if (attrs != null) { 97 | TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.custom_banner); 98 | int gravity = mTypedArray.getInt(R.styleable.custom_banner_indicatorGravity, 3); 99 | 100 | if (gravity == 1) { 101 | mIndicatorGravity = IndicatorGravity.LEFT; 102 | } else if (gravity == 2) { 103 | mIndicatorGravity = IndicatorGravity.RIGHT; 104 | } else if (gravity == 3) { 105 | mIndicatorGravity = IndicatorGravity.CENTER; 106 | } 107 | 108 | int style = mTypedArray.getInt(R.styleable.custom_banner_indicatorStyle, 3); 109 | 110 | if (style == 1) { 111 | mIndicatorStyle = IndicatorStyle.NONE; 112 | } else if (style == 2) { 113 | mIndicatorStyle = IndicatorStyle.NUMBER; 114 | } else if (style == 3) { 115 | mIndicatorStyle = IndicatorStyle.ORDINARY; 116 | } 117 | 118 | mIndicatorInterval = mTypedArray.getDimensionPixelOffset( 119 | R.styleable.custom_banner_indicatorInterval, DensityUtils.dp2px(context, 5)); 120 | int indicatorSelectRes = mTypedArray.getResourceId( 121 | R.styleable.custom_banner_indicatorSelectRes, 0); 122 | int indicatorUnSelectRes = mTypedArray.getResourceId( 123 | R.styleable.custom_banner_indicatorUnSelectRes, 0); 124 | if (indicatorSelectRes != 0) { 125 | mIndicatorSelectDrawable = context.getResources().getDrawable(indicatorSelectRes); 126 | } 127 | if (indicatorUnSelectRes != 0) { 128 | mIndicatorUnSelectDrawable = context.getResources().getDrawable(indicatorUnSelectRes); 129 | } 130 | mTypedArray.recycle(); 131 | } 132 | } 133 | 134 | private void init(Context context) { 135 | mContext = context; 136 | addBannerViewPager(context); 137 | addIndicatorLayout(context); 138 | addTextIndicator(context); 139 | } 140 | 141 | private void addBannerViewPager(Context context) { 142 | mBannerViewPager = new ViewPager(context); 143 | mBannerViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { 144 | @Override 145 | public void onPageScrolled(int position, float positionOffset, int positionOffsetP) { 146 | if (!isMarginal(position) && mOnPageChangeListener != null) { 147 | mOnPageChangeListener.onPageScrolled(getActualPosition(position), 148 | positionOffset, positionOffsetP); 149 | } 150 | } 151 | 152 | @Override 153 | public void onPageSelected(int position) { 154 | if (!isMarginal(position) && mOnPageChangeListener != null) { 155 | mOnPageChangeListener.onPageSelected(getActualPosition(position)); 156 | } 157 | updateIndicator(); 158 | } 159 | 160 | @Override 161 | public void onPageScrollStateChanged(int state) { 162 | int position = mBannerViewPager.getCurrentItem(); 163 | if (!isMarginal(position) && mOnPageChangeListener != null) { 164 | mOnPageChangeListener.onPageScrollStateChanged(state); 165 | } 166 | if (state == ViewPager.SCROLL_STATE_IDLE) { 167 | if (position == 0) { 168 | mScroller.setSudden(true); 169 | mBannerViewPager.setCurrentItem(mAdapter.getCount() - 2, true); 170 | mScroller.setSudden(false); 171 | } else if (position == mAdapter.getCount() - 1) { 172 | mScroller.setSudden(true); 173 | mBannerViewPager.setCurrentItem(1, true); 174 | mScroller.setSudden(false); 175 | } 176 | } 177 | } 178 | }); 179 | 180 | replaceViewPagerScroll(); 181 | this.addView(mBannerViewPager); 182 | } 183 | 184 | private void addIndicatorLayout(Context context) { 185 | //添加普通指示器容器 186 | mIndicatorLayout = new LinearLayout(context); 187 | LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 188 | lp.gravity = analysisGravity(mIndicatorGravity); 189 | int margins = DensityUtils.dp2px(context, 8); 190 | lp.setMargins(margins, 0, margins, margins); 191 | mIndicatorLayout.setGravity(Gravity.CENTER); 192 | mIndicatorLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE); 193 | mIndicatorLayout.setDividerDrawable(getDividerDrawable(mIndicatorInterval)); 194 | this.addView(mIndicatorLayout, lp); 195 | mIndicatorLayout.setVisibility(mIndicatorStyle == IndicatorStyle.ORDINARY ? VISIBLE : GONE); 196 | } 197 | 198 | private void addTextIndicator(Context context) { 199 | //添加数字指示器 200 | mNumberIndicator = new NumberIndicator(context); 201 | LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 202 | lp.gravity = analysisGravity(mIndicatorGravity); 203 | int margins = DensityUtils.dp2px(context, 8); 204 | lp.setMargins(margins, 0, margins, margins); 205 | this.addView(mNumberIndicator, lp); 206 | mNumberIndicator.setVisibility(GONE); 207 | } 208 | 209 | private Drawable getDividerDrawable(int interval) { 210 | // ShapeDrawable drawable = (ShapeDrawable) mContext.getResources().getDrawable( 211 | // R.drawable.indicator_divider); 212 | // drawable.setIntrinsicWidth(interval); 213 | ShapeDrawable drawable = new ShapeDrawable(); 214 | drawable.getPaint().setColor(Color.TRANSPARENT); 215 | drawable.setIntrinsicWidth(interval); 216 | return drawable; 217 | } 218 | 219 | @Override 220 | public void onWindowFocusChanged(boolean hasWindowFocus) { 221 | super.onWindowFocusChanged(hasWindowFocus); 222 | if (isTurning) { 223 | if (hasWindowFocus) { 224 | startTurning(mIntervalTime); 225 | } else { 226 | stopTurning(); 227 | isTurning = true; 228 | } 229 | } 230 | } 231 | 232 | private boolean isMarginal(int position) { 233 | return position == 0 || position == getCount() + 1; 234 | } 235 | 236 | /** 237 | * 设置轮播图数据 238 | * 239 | * @param creator 创建和更新轮播图View的接口 240 | * @param data 轮播图数据 241 | * @return 242 | */ 243 | public CustomBanner setPages(ViewCreator creator, List data) { 244 | mAdapter = new BannerPagerAdapter(mContext, creator, data); 245 | if (mOnPageClickListener != null) { 246 | mAdapter.setOnPageClickListener(mOnPageClickListener); 247 | } 248 | mBannerViewPager.setAdapter(mAdapter); 249 | if (data == null) { 250 | mIndicatorLayout.removeAllViews(); 251 | mBannerCount = 0; 252 | } else { 253 | mBannerCount = data.size(); 254 | initIndicator(data.size()); 255 | } 256 | setCurrentItem(0); 257 | updateIndicator(); 258 | return this; 259 | } 260 | 261 | /** 262 | * 设置指示器资源 263 | * 264 | * @param selectRes 选中的效果资源 265 | * @param unSelectRes 未选中的效果资源 266 | * @return 267 | */ 268 | public CustomBanner setIndicatorRes(int selectRes, int unSelectRes) { 269 | mIndicatorSelectDrawable = mContext.getResources().getDrawable(selectRes); 270 | mIndicatorUnSelectDrawable = mContext.getResources().getDrawable(unSelectRes); 271 | updateIndicator(); 272 | return this; 273 | } 274 | 275 | /** 276 | * 设置指示器资源 277 | * 278 | * @param select 选中的效果资源 279 | * @param unSelect 未选中的效果资源 280 | * @return 281 | */ 282 | public CustomBanner setIndicator(Drawable select, Drawable unSelect) { 283 | mIndicatorSelectDrawable = select; 284 | mIndicatorUnSelectDrawable = unSelect; 285 | updateIndicator(); 286 | return this; 287 | } 288 | 289 | /** 290 | * 设置指示器方向 291 | * 292 | * @param gravity 指示器方向 左、中、右三种 293 | * @return 294 | */ 295 | public CustomBanner setIndicatorGravity(IndicatorGravity gravity) { 296 | if (mIndicatorGravity != gravity) { 297 | mIndicatorGravity = gravity; 298 | setOrdinaryIndicatorGravity(gravity); 299 | setNumberIndicatorGravity(gravity); 300 | } 301 | return this; 302 | } 303 | 304 | private void setOrdinaryIndicatorGravity(IndicatorGravity gravity) { 305 | LayoutParams lp = (LayoutParams) mIndicatorLayout.getLayoutParams(); 306 | lp.gravity = analysisGravity(gravity); 307 | mIndicatorLayout.setLayoutParams(lp); 308 | } 309 | 310 | private void setNumberIndicatorGravity(IndicatorGravity gravity) { 311 | LayoutParams lp = (LayoutParams) mNumberIndicator.getLayoutParams(); 312 | lp.gravity = analysisGravity(gravity); 313 | mNumberIndicator.setLayoutParams(lp); 314 | } 315 | 316 | /** 317 | * 设置指示器类型 318 | * 319 | * @param style 指示器类型 普通指示器 数字指示器 没有指示器 三种 320 | * @return 321 | */ 322 | public CustomBanner setIndicatorStyle(IndicatorStyle style) { 323 | if (mIndicatorStyle != style) { 324 | mIndicatorStyle = style; 325 | mIndicatorLayout.setVisibility(mIndicatorStyle == IndicatorStyle.ORDINARY ? VISIBLE : GONE); 326 | mNumberIndicator.setVisibility(mIndicatorStyle == IndicatorStyle.NUMBER ? VISIBLE : GONE); 327 | updateIndicator(); 328 | } 329 | return this; 330 | } 331 | 332 | /** 333 | * 设置指示器间隔 334 | * 335 | * @param interval 336 | * @return 337 | */ 338 | public CustomBanner setIndicatorInterval(int interval) { 339 | if (mIndicatorInterval != interval) { 340 | mIndicatorInterval = interval; 341 | mIndicatorLayout.setDividerDrawable(getDividerDrawable(interval)); 342 | } 343 | return this; 344 | } 345 | 346 | public IndicatorGravity getIndicatorGravity() { 347 | return mIndicatorGravity; 348 | } 349 | 350 | private int analysisGravity(IndicatorGravity gravity) { 351 | if (gravity == IndicatorGravity.LEFT) { 352 | return Gravity.BOTTOM | Gravity.LEFT; 353 | } else if (gravity == IndicatorGravity.RIGHT) { 354 | return Gravity.BOTTOM | Gravity.RIGHT; 355 | } else { 356 | return Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL; 357 | } 358 | } 359 | 360 | /** 361 | * 启动轮播 362 | * 363 | * @param intervalTime 轮播间隔时间 364 | * @return 365 | */ 366 | public CustomBanner startTurning(long intervalTime) { 367 | if (isTurning) { 368 | stopTurning(); 369 | } 370 | isTurning = true; 371 | mIntervalTime = intervalTime; 372 | mTimeHandler.postDelayed(mTurningTask, mIntervalTime); 373 | return this; 374 | } 375 | 376 | /** 377 | * 停止轮播 378 | * 379 | * @return 380 | */ 381 | public CustomBanner stopTurning() { 382 | isTurning = false; 383 | mTimeHandler.removeCallbacks(mTurningTask); 384 | return this; 385 | } 386 | 387 | /** 388 | * 是否轮播 389 | * 390 | * @return 391 | */ 392 | public boolean isTurning() { 393 | return isTurning; 394 | } 395 | 396 | /** 397 | * 获取轮播间隔时间 398 | * 399 | * @return 400 | */ 401 | public long getIntervalTime() { 402 | return mIntervalTime; 403 | } 404 | 405 | public int getCount() { 406 | if (mAdapter == null || mAdapter.getCount() == 0) { 407 | return 0; 408 | } 409 | return mAdapter.getCount() - 2; 410 | } 411 | 412 | public CustomBanner setCurrentItem(int position) { 413 | if (position >= 0 && position < mAdapter.getCount()) { 414 | mBannerViewPager.setCurrentItem(position + 1); 415 | } 416 | return this; 417 | } 418 | 419 | public int getCurrentItem() { 420 | return getActualPosition(mBannerViewPager.getCurrentItem()); 421 | } 422 | 423 | private int getActualPosition(int position) { 424 | if (mAdapter == null || mAdapter.getCount() == 0) { 425 | return -1; 426 | } 427 | 428 | if (position == 0) { 429 | return getCount() - 1; 430 | } else if (position == getCount() + 1) { 431 | return 0; 432 | } else { 433 | return position - 1; 434 | } 435 | } 436 | 437 | private void initIndicator(int count) { 438 | mIndicatorLayout.removeAllViews(); 439 | if (count > 0) { 440 | for (int i = 0; i < count; i++) { 441 | ImageView imageView = new ImageView(mContext); 442 | LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( 443 | ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 444 | mIndicatorLayout.addView(imageView, lp); 445 | } 446 | } 447 | } 448 | 449 | /** 450 | * 更新指示器 451 | */ 452 | private void updateIndicator() { 453 | if (mIndicatorStyle == IndicatorStyle.ORDINARY) { 454 | int count = mIndicatorLayout.getChildCount(); 455 | int currentPage = getCurrentItem(); 456 | if (count > 0) { 457 | for (int i = 0; i < count; i++) { 458 | ImageView view = (ImageView) mIndicatorLayout.getChildAt(i); 459 | if (i == currentPage) { 460 | view.setImageDrawable(mIndicatorSelectDrawable); 461 | } else { 462 | view.setImageDrawable(mIndicatorUnSelectDrawable); 463 | } 464 | } 465 | } 466 | } else if (mIndicatorStyle == IndicatorStyle.NUMBER) { 467 | if (mBannerCount > 0) { 468 | mNumberIndicator.setVisibility(VISIBLE); 469 | mNumberIndicator.setText((getCurrentItem() + 1) + "/" + mBannerCount); 470 | } else { 471 | mNumberIndicator.setVisibility(GONE); 472 | } 473 | } 474 | } 475 | 476 | /** 477 | * 通过反射替换掉mBannerViewPager的mScroller属性。 478 | * 这样做是为了改变和控件ViewPager的滚动速度。 479 | */ 480 | private void replaceViewPagerScroll() { 481 | try { 482 | Field field = ViewPager.class.getDeclaredField("mScroller"); 483 | field.setAccessible(true); 484 | mScroller = new ViewPagerScroller(mContext, 485 | new AccelerateInterpolator()); 486 | field.set(mBannerViewPager, mScroller); 487 | } catch (Exception e) { 488 | } 489 | } 490 | 491 | /** 492 | * 设置轮播图的滚动速度 493 | * 494 | * @param scrollDuration 495 | */ 496 | public CustomBanner setScrollDuration(int scrollDuration) { 497 | mScroller.setScrollDuration(scrollDuration); 498 | return this; 499 | } 500 | 501 | public int getScrollDuration() { 502 | return mScroller.getScrollDuration(); 503 | } 504 | 505 | public CustomBanner setOnPageChangeListener(ViewPager.OnPageChangeListener l) { 506 | mOnPageChangeListener = l; 507 | return this; 508 | } 509 | 510 | public CustomBanner setOnPageClickListener(OnPageClickListener l) { 511 | if (mAdapter != null) { 512 | mAdapter.setOnPageClickListener(l); 513 | } 514 | 515 | mOnPageClickListener = l; 516 | return this; 517 | } 518 | 519 | /** 520 | * 通知数据刷新 521 | */ 522 | public void notifyDataSetChanged() { 523 | if (mAdapter != null) { 524 | mAdapter.notifyDataSetChanged(); 525 | } 526 | } 527 | 528 | public interface OnPageClickListener { 529 | void onPageClick(int position, T t); 530 | } 531 | 532 | /** 533 | * 创建和更新轮播图View的接口 534 | * 535 | * @param 536 | */ 537 | public interface ViewCreator { 538 | 539 | View createView(Context context, int position); 540 | 541 | void updateUI(Context context, View view, int position, T t); 542 | } 543 | } 544 | --------------------------------------------------------------------------------