前言
今天给大家带来一个新的控件–轮播图,网上已经有很多这类的博客来讲解如何实现的,那么我的这个有哪些特点呢?或是说有哪些不同呢?
满足了轮播图的基本要求,循环滑动,在最后一张切到第一张时可以平稳的过渡
简洁简洁简洁
扩展性强
如何使用
下面我们先展示两种效果图
1 默认效果
代码实现
//布局代码
<com.landptf.view.BannerM
android:id="@+id/bm_banner"
android:layout_width="match_parent"
android:layout_height="200dp" />
//java代码
BannerM banner = (BannerM) findViewById(R.id.bm_banner);
if (banner != null) {
banner.setBannerBeanList(bannerList).show();
}
//初始化数据
private void initData() {
bannerList = new ArrayList<>(4);
BannerBean banner1 = new BannerBean("测试图片1", url1, "");
BannerBean banner2 = new BannerBean("测试图片2", url2, "");
BannerBean banner3 = new BannerBean("测试图片3", url3, "");
BannerBean banner4 = new BannerBean("测试图片4", url4, "");
bannerList.add(banner1);
bannerList.add(banner2);
bannerList.add(banner3);
bannerList.add(banner4);
}
其实关键代码就一行,这里面用到了BannerBean的实体类,有三个参数,分别是图片的描述文字,图片地址,点击后对应的链接
以上全部都是默认值,下面来看一下都哪些可以自定义
2 自定义效果
图1和图2主要有以下几点不同
1 指示器和文字的位置结构,这里面我只实现了两种,大家也可以下载源码后扩展
2 圆点指示器选中后的颜色
3 自动播放的时间间隔
4 支持图片未加载出来之前显示默认图片
自定义效果的代码实现
下面通过xml和java代码来分别演示一下图2的实现
1 xml
<com.landptf.view.BannerM
android:id="@+id/bm_banner"
android:layout_width="match_parent"
android:layout_height="200dp"
landptf:defaultImageDrawable="@drawable/default_image"
landptf:intervalTime="3"
landptf:indexPosition="bottom"
landptf:indexColor="@color/colorPrimary"
/>
BannerM banner = (BannerM) findViewById(R.id.bm_banner);
if (banner != null) {
banner.setBannerBeanList(bannerList)
.setOnItemClickListener(new BannerM.OnItemClickListener() {
@Override
public void onItemClick(int position) {
Log.e("landptf", "position = " + position);
}
})
.show();
}
2 java
<com.landptf.view.BannerM
android:id="@+id/bm_banner"
android:layout_width="match_parent"
android:layout_height="200dp" />
BannerM banner = (BannerM) findViewById(R.id.bm_banner);
if (banner != null) {
banner.setBannerBeanList(bannerList)
.setDefaultImageResId(R.drawable.default_image)
.setIndexPosition(BannerM.INDEX_POSITION_BOTTOM)
.setIndexColor(getResources().getColor(R.color.colorPrimary))
.setIntervalTime(3)
.setOnItemClickListener(new BannerM.OnItemClickListener() {
@Override
public void onItemClick(int position) {
Log.e("landptf", "position = " + position);
}
})
.show();
}
以上两种代码实现的效果完全等价,在java代码中都是通过链式调用,使代码看起来更加的简洁。
有木有很方便,大大的减少了代码量,而且是可以直接拿来用的。好了下面我们来看一下实现的代码。
实现
图片下载集成了Picasso,有对Picasso不熟悉的童鞋可以看一下我之前的博客图片加载利器之Picasso(二)基本用法
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="@+id/vp_banner"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ViewStub
android:id="@+id/vs_index_right"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout="@layout/viewstub_banner_m_index_right" />
<ViewStub
android:id="@+id/vs_index_bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout="@layout/viewstub_banner_m_index_bottom" />
</RelativeLayout>
ViewStub的引用代码这里就不给出,大家可以访问我的git查看,文末会给出地址
package com.landptf.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.landptf.R;
import com.landptf.bean.BannerBean;
import com.landptf.util.ConvertM;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class BannerM extends RelativeLayout {
public static final int INDEX_POSITION_RIGHT = 0x100;
public static final int INDEX_POSITION_BOTTOM = 0x101;
private static final int HANDLE_UPDATE_INDEX = 0;
private Context mContext;
private ViewPager vpBanner;
private ViewPagerAdapter adapter;
private OnItemClickListener mOnItemClickListener;
//装载ImageView控件的list
private List<ImageView> ivList;
//圆点指示器控件
private List<View> vList;
//控制圆点View的形状,未选中的颜色
private GradientDrawable gradientDrawable;
//控制圆点View的形状,选中的颜色
private GradientDrawable gradientDrawableSelected;
//选中圆点的颜色值,默认为#FF3333
private int indexColorResId;
//图片对应的文字描述
private TextView tvText;
//自动滑动的定时器
private ScheduledExecutorService scheduledExecutorService;
//当前加载到第几页
private int currentIndex = 0;
//默认背景图
private int defaultImageResId;
private Drawable defaultImageDrawable = null;
//自动轮播的时间间隔(s)
private int intervalTime = 5;
//轮播图需要的数据列表
private List<BannerBean> bannerBeanList;
//圆点指示器的位置,提供两种布局
private int indexPosition = INDEX_POSITION_RIGHT;
public BannerM(Context context) {
this(context, null);
}
public BannerM(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BannerM(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
mContext = context;
LayoutInflater.from(context).inflate(R.layout.view_banner_m, this, true);
vpBanner = (ViewPager) findViewById(R.id.vp_banner);
TypedArray a = getContext().obtainStyledAttributes(
attrs, R.styleable.bannerM, defStyle, 0);
if (a != null) {
defaultImageDrawable = a.getDrawable(R.styleable.bannerM_defaultImageDrawable);
intervalTime = a.getInteger(R.styleable.bannerM_intervalTime, 5);
indexPosition = a.getInteger(R.styleable.bannerM_indexPosition, INDEX_POSITION_RIGHT);
ColorStateList indexColorList = a.getColorStateList(R.styleable.bannerM_indexColor);
if (indexColorList != null) {
indexColorResId = indexColorList.getColorForState(getDrawableState(), 0);
}
a.recycle();
}
}
public BannerM setDefaultImageResId(int defaultImageResId) {
this.defaultImageResId = defaultImageResId;
return this;
}
public BannerM setDefaultImageDrawable(Drawable defaultImageDrawable) {
this.defaultImageDrawable = defaultImageDrawable;
return this;
}
public BannerM setIntervalTime(int intervalTime) {
this.intervalTime = intervalTime;
return this;
}
public BannerM setIndexPosition(int indexPosition) {
this.indexPosition = indexPosition;
return this;
}
public BannerM setIndexColor(int indexColor) {
this.indexColorResId = indexColor;
return this;
}
public BannerM setBannerBeanList(List<BannerBean> bannerBeanList) {
this.bannerBeanList = bannerBeanList;
return this;
}
public BannerM setOnItemClickListener(@Nullable OnItemClickListener listener) {
mOnItemClickListener = listener;
return this;
}
public void show() {
if (bannerBeanList == null || bannerBeanList.size() == 0) {
throw new IllegalArgumentException("bannerBeanList == null");
}
initImageViewList();
initIndexList();
vpBanner.addOnPageChangeListener(new OnPageChangeListener());
adapter = new ViewPagerAdapter();
vpBanner.setAdapter(adapter);
//定时器开始工作
startPlay();
}
private void initIndexList() {
int count = bannerBeanList.size();
vList = new ArrayList<>(count);
LinearLayout llIndex;
if (indexPosition == INDEX_POSITION_RIGHT) {
ViewStub vsIndexRight = (ViewStub) findViewById(R.id.vs_index_right);
vsIndexRight.inflate();
llIndex = (LinearLayout) findViewById(R.id.ll_index_right);
tvText = (TextView) findViewById(R.id.tv_text);
} else {
ViewStub vsIndexBottom = (ViewStub) findViewById(R.id.vs_index_bottom);
vsIndexBottom.inflate();
llIndex = (LinearLayout) findViewById(R.id.ll_index_bottom);
tvText = (TextView) findViewById(R.id.tv_text);
}
//默认第一张图片的文字描述
tvText.setText(bannerBeanList.get(0).getText());
//使用GradientDrawable构造圆形控件
gradientDrawable = new GradientDrawable();
gradientDrawable.setShape(GradientDrawable.OVAL);
gradientDrawable.setColor(mContext.getResources().getColor(R.color.text));
gradientDrawableSelected = new GradientDrawable();
gradientDrawableSelected.setShape(GradientDrawable.OVAL);
if (indexColorResId != 0) {
gradientDrawableSelected.setColor(indexColorResId);
} else {
gradientDrawableSelected.setColor(mContext.getResources().getColor(R.color.mainColor));
}
for (int i = 0; i < count; i++) {
View view = new View(mContext);
LinearLayout.LayoutParams lpView = new LinearLayout.LayoutParams(ConvertM.dp2px(mContext, 8), ConvertM.dp2px(mContext, 8));
lpView.rightMargin = ConvertM.dp2px(mContext, 4);
view.setLayoutParams(lpView);
if (0 == i) {
view.setBackgroundDrawable(gradientDrawableSelected);
} else {
view.setBackgroundDrawable(gradientDrawable);
}
view.bringToFront();
vList.add(view);
llIndex.addView(view);
}
}
private void initImageViewList() {
int count = bannerBeanList.size();
ivList = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
final ImageView imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
ivList.add(imageView);
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mOnItemClickListener.onItemClick(getPosition(imageView));
}
});
if (defaultImageResId != 0) {
Picasso.with(mContext)
.load(bannerBeanList.get(i).getUrl())
.placeholder(defaultImageResId)
.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.into(imageView);
} else if (defaultImageDrawable != null) {
Picasso.with(mContext)
.load(bannerBeanList.get(i).getUrl())
.placeholder(defaultImageDrawable)
.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.into(imageView);
} else {
Picasso.with(mContext)
.load(bannerBeanList.get(i).getUrl())
.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.into(imageView);
}
}
}
private void startPlay() {
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
currentIndex++;
handler.obtainMessage(HANDLE_UPDATE_INDEX).sendToTarget();
}
}, intervalTime, intervalTime, TimeUnit.SECONDS);
}
private int getPosition(ImageView item) {
for (int i = 0; i < ivList.size(); i++) {
if (item == ivList.get(i)) {
return i;
}
}
return -1;
}
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case HANDLE_UPDATE_INDEX:
vpBanner.setCurrentItem(currentIndex);
break;
default:
break;
}
}
};
private class OnPageChangeListener implements ViewPager.OnPageChangeListener {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
currentIndex = position;
for (int i = 0; i < bannerBeanList.size(); i++) {
if (position % ivList.size() == i) {
vList.get(i).setBackgroundDrawable(gradientDrawableSelected);
} else {
vList.get(i).setBackgroundDrawable(gradientDrawable);
}
tvText.setText(bannerBeanList.get(position % ivList.size()).getText());
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
private class ViewPagerAdapter extends PagerAdapter {
@Override
public void destroyItem(View container, int position, Object object) {
}
@Override
public Object instantiateItem(View container, int position) {
position %= ivList.size();
if (position<0){
position = ivList.size()+position;
}
ImageView imageView = ivList.get(position);
ViewParent vp =imageView.getParent();
if (vp!=null){
ViewGroup parent = (ViewGroup)vp;
parent.removeView(imageView);
}
((ViewPager) container).addView(imageView);
return imageView;
}
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {
}
@Override
public void finishUpdate(View arg0) {
}
}
public interface OnItemClickListener {
void onItemClick(int position);
}
}
这篇文章就介绍到这里了,点击这里查看源码
下面是测试用的图片:
您可能感兴趣的文章:Android开发在轮播图片上加入点击事件的方法Android实现自定义轮播图片控件示例Android实现自定义轮播图片控件详解Android实现轮播图片展示效果Android开发实现的自动换图片、轮播图效果示例Android ViewPager实现轮播图效果Android实现炫酷轮播图效果Android实现ViewPage轮播图效果Android自定义控件实现简单的轮播图控件Android轮播图点击图片放大效果的实现方法