輪播圖是app必備的元素之一常空。今天來(lái)教大家如何簡(jiǎn)單使用他。
說(shuō)明:
一,使用的Androidstudio版本為3.2.1
二,使用的ConvenientBanner版本為2.1.4最新版,和以前的版本有一定區(qū)別
三,ConvenientBanner是github大神封裝的一個(gè)通用廣告欄控件孩饼。使用起來(lái)簡(jiǎn)單高效愿阐,但是沒(méi)有簡(jiǎn)單使用的詳細(xì)文檔。
github地址為:https://github.com/Bigkoo/Android-ConvenientBanner
展示效果:
banner.gif
現(xiàn)在正式開始
1回挽,在build.gradle中做如下代碼1--6步驟所示配置没咙。
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.admin.jsbanner"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
//1,增加這個(gè)東西
allprojects {
repositories {
maven { url "https://jitpack.io" }
maven { url "https://maven.google.com" }
flatDir {
dirs 'libs'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
//2,導(dǎo)入design,原因是通用廣告欄ConvenientBanner使用了里面的元素
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
//3千劈,butterKnife祭刚,不是必須添加,如果你使用的項(xiàng)目使用的是DataBinding墙牌,可以不添加該依賴
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
//4涡驮,通用廣告欄ConvenientBanner
implementation 'com.bigkoo:ConvenientBanner:2.1.4'
//5,圖片緩存庫(kù)
implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.4'
//glide圖片庫(kù)
implementation 'com.github.bumptech.glide:glide:4.8.0'
}
2喜滨,在AndroidManifest.xml中增加聯(lián)網(wǎng)的權(quán)限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.admin.jsbanner">
//因?yàn)榧虞d網(wǎng)絡(luò)圖片捉捅,需要聯(lián)網(wǎng)的權(quán)限
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".App"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
3,新建一個(gè)app類虽风,ImageLoader需要在這里面初始化棒口,如果你只需要使用glide加載網(wǎng)絡(luò)圖片的方式,那這個(gè)就不需要添加
package com.example.admin.jsbanner;
import android.app.Application;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
/**
* author : zlf
* date : 2018/11/22
* blog :http://www.reibang.com/u/281e9668a5a6
*/
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
//創(chuàng)建全局的配置來(lái)初始化ImageLoader
ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(this);
ImageLoader.getInstance().init(configuration);
}
}
4辜膝,在mipmap中加入兩張指示器的圖片ic_page_indicator.png和ic_page_indicator_focused.png
5无牵,新建兩個(gè)子布局item_banner1.xml和item_banner2.xml,輪播圖默認(rèn)加載這兩個(gè)布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="210dp"
android:orientation="vertical">
<ImageView
android:id="@+id/iv_banner1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/ic_launcher" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="210dp"
android:orientation="vertical">
<ImageView
android:id="@+id/iv_banner2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/ic_launcher" />
</LinearLayout>
6厂抖,在主activity對(duì)應(yīng)的xml中添加ConvenientBanner茎毁,因?yàn)槭褂昧藘煞N加載方式,所以展示了兩個(gè)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<com.bigkoo.convenientbanner.ConvenientBanner
android:id="@+id/cb_test1"
android:layout_width="match_parent"
android:layout_height="210dp"
android:background="@mipmap/ic_launcher"
app:canLoop="true" />
<com.bigkoo.convenientbanner.ConvenientBanner
android:id="@+id/cb_test2"
android:layout_width="match_parent"
android:layout_height="210dp"
android:background="@mipmap/ic_launcher"
app:canLoop="true" />
</LinearLayout>
7忱辅,使用了兩種加載方式七蜘,如開篇展示圖所示,有如下注意事項(xiàng):
- initBanner1();使用的是ImageLoader加載方式
- initBanner2();使用的是glide加載圖片的方式
- 在onResume和onPause中開始和停止輪播圖
- mCanLoop用來(lái)控制如果是一張圖片不能滑動(dòng)墙懂,不能自動(dòng)輪播崔梗,不展示指示器
package com.example.admin.jsbanner;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
/**
* author : zlf
* date : 2018/11/22
* blog :http://www.reibang.com/u/281e9668a5a6
*/
public class MainActivity extends AppCompatActivity {
private Unbinder unbinder;
@BindView(R.id.cb_test1)
ConvenientBanner cbTest1;
@BindView(R.id.cb_test2)
ConvenientBanner cbTest2;
// TODO: 2018/11/22 是否自動(dòng)輪播,控制如果是一張圖片,不能滑動(dòng)
private boolean mCanLoop = true;
private ArrayList<String> arrayList;
private DisplayImageOptions options;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
unbinder = ButterKnife.bind(this);
initView();
initBanner1();
initBanner2();
}
@Override
protected void onResume() {
super.onResume();
//開始執(zhí)行輪播垒在,并設(shè)置輪播時(shí)長(zhǎng)
cbTest1.startTurning(4000);
cbTest2.startTurning(2000);
}
@Override
protected void onPause() {
super.onPause();
//停止輪播
cbTest1.stopTurning();
cbTest2.stopTurning();
}
@Override
protected void onDestroy() {
super.onDestroy();
unbinder.unbind();
}
/**
* 初始化
* 添加三張展示照片蒜魄,網(wǎng)上隨便找的扔亥,正常形式是調(diào)用接口從自己的后臺(tái)服務(wù)器拿取
*/
private void initView() {
arrayList = new ArrayList<>();
arrayList.add("http://img2.imgtn.bdimg.com/it/u=1447362014,2103397884&fm=200&gp=0.jpg");
arrayList.add("http://img1.imgtn.bdimg.com/it/u=111342610,3492888501&fm=26&gp=0.jpg");
arrayList.add("http://imgsrc.baidu.com/imgad/pic/item/77094b36acaf2eddc8c37dc7861001e9390193e9.jpg");
}
/**
* 初始化輪播圖1
* setPageIndicator 設(shè)置指示器樣式
* setPageIndicatorAlign 設(shè)置指示器位置
* setPointViewVisible 設(shè)置指示器是否顯示
* setCanLoop 設(shè)置是否輪播
* setOnItemClickListener 設(shè)置每一張圖片的點(diǎn)擊事件
*/
private void initBanner1() {
// TODO: 2018/11/22 控制如果只有一張網(wǎng)絡(luò)圖片,不能滑動(dòng)谈为,不能輪播
if(arrayList.size()<=1){
mCanLoop=false;
}
cbTest1.setPages(new CBViewHolderCreator() {
@Override
public Holder createHolder(View itemView) {
return new NetImageHolderView1(itemView);
}
@Override
public int getLayoutId() {
//設(shè)置加載哪個(gè)布局
return R.layout.item_banner1;
}
}, arrayList)
.setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused})
.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
.setPointViewVisible(mCanLoop)
.setCanLoop(mCanLoop)
.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(int position) {
Toast.makeText(MainActivity.this, "你點(diǎn)擊了cbTest1的第" + position + "張圖片", Toast.LENGTH_SHORT).show();
}
});
}
/**
* 初始化輪播圖2
*/
private void initBanner2() {
cbTest2.setPages(new CBViewHolderCreator() {
@Override
public Holder createHolder(View itemView) {
return new NetImageHolderView2(itemView);
}
@Override
public int getLayoutId() {
return R.layout.item_banner2;
}
}, arrayList)
.setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused})
.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
.setPointViewVisible(mCanLoop)
.setCanLoop(mCanLoop)
.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(int position) {
Toast.makeText(MainActivity.this, "你點(diǎn)擊了cbTest2的第" + position + "張圖片", Toast.LENGTH_SHORT).show();
}
});
}
/**
* 輪播圖1 對(duì)應(yīng)的holder
*/
public class NetImageHolderView1 extends Holder<String> {
private ImageView mImageView;
//構(gòu)造器
public NetImageHolderView1(View itemView) {
super(itemView);
}
@Override
protected void initView(View itemView) {
//找到對(duì)應(yīng)展示圖片的imageview
mImageView = itemView.findViewById(R.id.iv_banner1);
//設(shè)置圖片加載模式為鋪滿旅挤,具體請(qǐng)搜索 ImageView.ScaleType.FIT_XY
mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
//初始化options,可以加載不同情況下的默認(rèn)圖片
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.mipmap.ic_launcher)//設(shè)置加載圖片時(shí)候的圖片
.showImageForEmptyUri(R.mipmap.ic_launcher)//設(shè)置圖片uri為空或是錯(cuò)誤的時(shí)候顯示的圖片
.showImageOnFail(R.mipmap.ic_launcher)//設(shè)置獲取圖片失敗的默認(rèn)圖片
.cacheInMemory(true)//設(shè)置內(nèi)存緩存
.cacheOnDisk(true)//設(shè)置外存緩存
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
}
@Override
public void updateUI(String data) {
//使用ImageLoader加載圖片
ImageLoader.getInstance().displayImage(data, mImageView, options);
}
}
/**
* 輪播圖2 對(duì)應(yīng)的holder
*/
public class NetImageHolderView2 extends Holder<String> {
private ImageView mImageView;
//構(gòu)造器
public NetImageHolderView2(View itemView) {
super(itemView);
}
@Override
protected void initView(View itemView) {
//找到對(duì)應(yīng)展示圖片的imageview
mImageView = itemView.findViewById(R.id.iv_banner2);
//設(shè)置圖片加載模式為鋪滿伞鲫,具體請(qǐng)搜索 ImageView.ScaleType.FIT_XY
mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
}
@Override
public void updateUI(String data) {
//使用glide加載更新圖片
Glide.with(MainActivity.this).load(data).into(mImageView);
}
}
}
7粘茄,項(xiàng)目結(jié)構(gòu)和github地址
項(xiàng)目結(jié)構(gòu):
image.png
demo地址:https://github.com/mamumu/jsBanner
如果有發(fā)現(xiàn)錯(cuò)誤歡迎指正我及時(shí)修改,如果有好的建議歡迎留言秕脓。如果覺(jué)得對(duì)你有幫助歡迎給小星星柒瓣,謝謝。