1.Banner介绍
现在的绝大数app都有banner界面,实现循环播放多个广告图片和手动滑动循环等功能。
2.使用环境配置(具体可见github开源项目)
(1)添加依赖
在build.gradle(app)文件内添加依赖
dependencies{
compile 'com.youth.banner:banner:1.4.10' //最新版本
implementation 'com.github.bumptech.glide:glide:3.7.0'
}
(2)添加权限到你的 AndroidManifest.xml
<!-- if you want to load images from the internet -->
<uses-permission android:name="android.permission.INTERNET" /> <!-- if you want to load images from a file OR from the internet -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
(3)在布局文件中添加Banner,可以设置自定义属性
<com.youth.banner.Banner
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/banner"
android:layout_width="match_parent"
android:layout_height="高度自己设置" />
3.使用案例
(1)xml文件布局
<?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.youth.banner.Banner xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/banner"
android:layout_width="match_parent"
android:layout_height="150dp" /> </LinearLayout>
(2)java后台
<1>图片加载器
package com.example.administrator.test63advertisebanner; import android.content.Context;
import android.widget.ImageView; import com.bumptech.glide.Glide;
import com.youth.banner.loader.ImageLoader; /**
* 图片加载器
*/
public class GlideImageLoader extends ImageLoader {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
//Glide 加载图片简单用法
Glide.with(context)
.load(path)
.into(imageView);
}
}
<2>MainActivity.java
package com.example.administrator.test63advertisebanner; import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; import com.youth.banner.Banner;
import com.youth.banner.BannerConfig; import java.util.ArrayList;
import java.util.List; public class MainActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//资源文件
List<Integer> images=new ArrayList<>();
List<String> titleList=new ArrayList<>();
images.add(R.mipmap.a);
images.add(R.mipmap.b);
images.add(R.mipmap.c);
images.add(R.mipmap.d);
titleList.add("iphonexr牛逼");
titleList.add("手机王牌对王牌");
titleList.add("华为P30");
titleList.add("梁山伯与祝英台");
Banner banner = findViewById(R.id.banner);
//设置内置样式,共有六种可以点入方法内逐一体验使用。
banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
//设置图片加载器
banner.setImageLoader(new GlideImageLoader());
//设置图片集合
banner.setImages(images);
//设置轮播图的标题集合
banner.setBannerTitles(titleList);
//banner设置方法全部调用完毕时最后调用
banner.start();
}
}
4.效果图