近来项目忙完了,觉得自己的自动广告轮播 蛮不错的 ,所以分享出来。先说说他的功能,第一能够实现自动轮播 图片 ,第二可以修改自动更换广告条的小点默认是圆形的 可以修改为小的正方向 ,同时 还可以修改 原点所在的位置 居中 居左 居 右,以及颜色改变等等。
1.代码如下:
/**
* Created by xiaomo on 2015/8/9.
*/
public class BannerLayout extends RelativeLayout {

private ViewPager pager;
//指示器容器
private LinearLayout indicatorContainer;private Drawable unSelectedDrawable;
private Drawable selectedDrawable;private int WHAT_AUTO_PLAY = 1000;private boolean isAutoPlay = true;private int itemCount;/**点选中的颜色**/
private int selectedIndicatorColor = 0xffff0000;
/**未选中的颜色**/
private int unSelectedIndicatorColor = 0x88888888;
/**点的类型 、oval(圆点)、rect(方形)**/
private Shape indicatorShape = Shape.oval;
/**选中小圆点高**/
private int selectedIndicatorHeight = 6;
/**选中小圆点宽**/
private int selectedIndicatorWidth = 6;
/**未选中小圆点高**/
private int unSelectedIndicatorHeight = 6;
/**未选中小圆点宽**/
private int unSelectedIndicatorWidth = 6;
/**scroll的持续时间**/
private Position indicatorPosition = Position.centerBottom;
/**滑动的时间*/
private int autoPlayDuration = 3000;
/**scroll的持续时间**/
private int scrollDuration = 1100;
/**滑动小圆点间距**/
private int indicatorSpace = 3;
/**滑动小圆点边缘的间距**/
private int indicatorMargin = 10;private enum Shape {rect, oval
}private enum Position {centerBottom,rightBottom,leftBottom,centerTop,rightTop,leftTop
}private OnBannerItemClickListener onBannerItemClickListener;private Handler handler = new Handler(new Handler.Callback() {@Overridepublic boolean handleMessage(Message msg) {if (msg.what == WHAT_AUTO_PLAY) {if(null == pager){return false;}pager.setCurrentItem(pager.getCurrentItem() + 1, true);handler.sendEmptyMessageDelayed(WHAT_AUTO_PLAY, autoPlayDuration);}return false;}
});public BannerLayout(Context context) {super(context);init(null, 0);
}public BannerLayout(Context context, AttributeSet attrs) {super(context, attrs);init(attrs, 0);
}public BannerLayout(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);init(attrs, defStyleAttr);
}private void init(AttributeSet attrs, int defStyle) {TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.BannerLayoutStyle, defStyle, 0);selectedIndicatorColor = array.getColor(R.styleable.BannerLayoutStyle_selectedIndicatorColor, selectedIndicatorColor);unSelectedIndicatorColor = array.getColor(R.styleable.BannerLayoutStyle_unSelectedIndicatorColor, unSelectedIndicatorColor);int shape = array.getInt(R.styleable.BannerLayoutStyle_indicatorShape, Shape.oval.ordinal());for (Shape shape1 : Shape.values()) {if (shape1.ordinal() == shape) {indicatorShape = shape1;break;}}selectedIndicatorHeight = (int) array.getDimension(R.styleable.BannerLayoutStyle_selectedIndicatorHeight, selectedIndicatorHeight);selectedIndicatorWidth = (int) array.getDimension(R.styleable.BannerLayoutStyle_selectedIndicatorWidth, selectedIndicatorWidth);unSelectedIndicatorHeight = (int) array.getDimension(R.styleable.BannerLayoutStyle_unSelectedIndicatorHeight, unSelectedIndicatorHeight);unSelectedIndicatorWidth = (int) array.getDimension(R.styleable.BannerLayoutStyle_unSelectedIndicatorWidth, unSelectedIndicatorWidth);int position = array.getInt(R.styleable.BannerLayoutStyle_indicatorPosition, Position.centerBottom.ordinal());for (Position position1 : Position.values()) {if (position == position1.ordinal()) {indicatorPosition = position1;}}indicatorSpace = (int) array.getDimension(R.styleable.BannerLayoutStyle_indicatorSpace, indicatorSpace);indicatorMargin = (int) array.getDimension(R.styleable.BannerLayoutStyle_indicatorMargin, indicatorMargin);autoPlayDuration = array.getInt(R.styleable.BannerLayoutStyle_autoPlayDuration, autoPlayDuration);scrollDuration = array.getInt(R.styleable.BannerLayoutStyle_scrollDuration, scrollDuration);isAutoPlay = array.getBoolean(R.styleable.BannerLayoutStyle_isAutoPlay, isAutoPlay);array.recycle();//绘制未选中状态图形LayerDrawable unSelectedLayerDrawable;LayerDrawable selectedLayerDrawable;GradientDrawable unSelectedGradientDrawable;unSelectedGradientDrawable = new GradientDrawable();//绘制选中状态图形GradientDrawable selectedGradientDrawable;selectedGradientDrawable = new GradientDrawable();switch (indicatorShape) {case rect:unSelectedGradientDrawable.setShape(GradientDrawable.RECTANGLE);selectedGradientDrawable.setShape(GradientDrawable.RECTANGLE);break;case oval:unSelectedGradientDrawable.setShape(GradientDrawable.OVAL);selectedGradientDrawable.setShape(GradientDrawable.OVAL);break;}unSelectedGradientDrawable.setColor(unSelectedIndicatorColor);unSelectedGradientDrawable.setSize(unSelectedIndicatorWidth, unSelectedIndicatorHeight);unSelectedLayerDrawable = new LayerDrawable(new Drawable[]{unSelectedGradientDrawable});unSelectedDrawable = unSelectedLayerDrawable;selectedGradientDrawable.setColor(selectedIndicatorColor);selectedGradientDrawable.setSize(selectedIndicatorWidth, selectedIndicatorHeight);selectedLayerDrawable = new LayerDrawable(new Drawable[]{selectedGradientDrawable});selectedDrawable = selectedLayerDrawable;}//添加本地图片路径
public void setViewRes(List<Integer> viewRes) {List<View> views = new ArrayList<View>();itemCount = viewRes.size();//主要是解决当item为小于3个的时候滑动有问题,这里将其拼凑成3个以上if (itemCount < 1) {//当item个数0throw new IllegalStateException("item count not equal zero");} else if (itemCount < 2) {//当item个数为1views.add(getImageView(viewRes.get(0), 0));views.add(getImageView(viewRes.get(0), 0));views.add(getImageView(viewRes.get(0), 0));} else if (itemCount < 3) {//当item个数为2views.add(getImageView(viewRes.get(0), 0));views.add(getImageView(viewRes.get(1), 1));views.add(getImageView(viewRes.get(0), 0));views.add(getImageView(viewRes.get(1), 1));} else {for (int i = 0; i < viewRes.size(); i++) {views.add(getImageView(viewRes.get(i), i));}}setViews(views);
}*private SimpleDraweeView  getImageView (Integer res, final int position) {SimpleDraweeView  imageView = new SimpleDraweeView (getContext());imageView.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {if (onBannerItemClickListener != null) {onBannerItemClickListener.onItemClick(position);}}});*imageView.setHierarchy(AppContext.setHierarchy(imageView,R.mipmap.icon_notad));AppContext.loadPicture(imageView,res+"");return imageView;
}//添加网络图片路径
public void setViewUrls(List<String> urls) {List<View> views = new ArrayList<View>();itemCount = urls.size();//主要是解决当item为小于3个的时候滑动有问题,这里将其拼凑成3个以上if (itemCount < 1) {//当item个数0throw new IllegalStateException("item count not equal zero");} else if (itemCount < 2) { //当item个数为1views.add(getImageView(urls.get(0), 0));views.add(getImageView(urls.get(0), 0));views.add(getImageView(urls.get(0), 0));} else if (itemCount < 3) {//当item个数为2views.add(getImageView(urls.get(0), 0));views.add(getImageView(urls.get(1), 1));views.add(getImageView(urls.get(0), 0));views.add(getImageView(urls.get(1), 1));} else {for (int i = 0; i < urls.size(); i++) {views.add(getImageView(urls.get(i), i));}}setViews(views);
}private SimpleDraweeView getImageView(String url, final int position) {SimpleDraweeView imageView = new SimpleDraweeView(getContext());imageView.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {if (onBannerItemClickListener != null) {onBannerItemClickListener.onItemClick(position);}}});imageView.setHierarchy(AppContext.setHierarchy(imageView, R.mipmap.icon_notad));AppContext.loadPicture(imageView, url + "");return imageView;
}//添加任意View视图
private void setViews(final List<View> views) {//初始化pagerpager = new ViewPager(getContext());//添加viewpager到SliderLayoutaddView(pager);setSliderTransformDuration(scrollDuration);//初始化indicatorContainerindicatorContainer = new LinearLayout(getContext());indicatorContainer.setGravity(Gravity.CENTER_VERTICAL);LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);switch (indicatorPosition) {case centerBottom:params.addRule(RelativeLayout.CENTER_HORIZONTAL);params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);break;case centerTop:params.addRule(RelativeLayout.CENTER_HORIZONTAL);params.addRule(RelativeLayout.ALIGN_PARENT_TOP);break;case leftBottom:params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);break;case leftTop:params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);params.addRule(RelativeLayout.ALIGN_PARENT_TOP);break;case rightBottom:params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);break;case rightTop:params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);params.addRule(RelativeLayout.ALIGN_PARENT_TOP);break;}//设置marginparams.setMargins(indicatorMargin, indicatorMargin, indicatorMargin, indicatorMargin);//添加指示器容器布局到SliderLayoutaddView(indicatorContainer, params);//初始化指示器,并添加到指示器容器布局for (int i = 0; i < itemCount; i++) {ImageView indicator = new ImageView(getContext());indicator.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));indicator.setPadding(indicatorSpace, indicatorSpace, indicatorSpace, indicatorSpace);indicator.setImageDrawable(unSelectedDrawable);indicatorContainer.addView(indicator);}LoopPagerAdapter pagerAdapter = new LoopPagerAdapter(views);pager.setAdapter(pagerAdapter);//设置当前item到Integer.MAX_VALUE中间的一个值,看起来像无论是往前滑还是往后滑都是ok的//如果不设置,用户往左边滑动的时候已经划不动了int targetItemPosition = Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2 % itemCount;pager.setCurrentItem(targetItemPosition);switchIndicator(targetItemPosition % itemCount);//addOnPageChangeListenerpager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {@Overridepublic void onPageSelected(int position) {switchIndicator(position % itemCount);}});startAutoPlay();}public void setSliderTransformDuration(int duration) {try {Field mScroller = ViewPager.class.getDeclaredField("mScroller");mScroller.setAccessible(true);FixedSpeedScroller scroller = new FixedSpeedScroller(pager.getContext(), null, duration);mScroller.set(pager, scroller);} catch (Exception e) {}
}/*** 开始自动轮播*/
public void startAutoPlay() {stopAutoPlay(); // 避免重复消息if (isAutoPlay) {handler.sendEmptyMessageDelayed(WHAT_AUTO_PLAY, autoPlayDuration);}
}@Override
protected void onWindowVisibilityChanged(int visibility) {super.onWindowVisibilityChanged(visibility);if (visibility == VISIBLE) {startAutoPlay();} else {stopAutoPlay();}
}/*** 停止自动轮播*/
public void stopAutoPlay() {if (isAutoPlay) {handler.removeMessages(WHAT_AUTO_PLAY);}
}@Override
public boolean dispatchTouchEvent(MotionEvent ev) {switch (ev.getAction()) {case MotionEvent.ACTION_DOWN:stopAutoPlay();break;case MotionEvent.ACTION_CANCEL:case MotionEvent.ACTION_UP:startAutoPlay();break;}return super.dispatchTouchEvent(ev);
}/*** 切换指示器状态** @param currentPosition 当前位置*/
private void switchIndicator(int currentPosition) {for (int i = 0; i < indicatorContainer.getChildCount(); i++) {((ImageView) indicatorContainer.getChildAt(i)).setImageDrawable(i == currentPosition ? selectedDrawable : unSelectedDrawable);}
}public void setOnBannerItemClickListener(OnBannerItemClickListener onBannerItemClickListener) {this.onBannerItemClickListener = onBannerItemClickListener;
}public interface OnBannerItemClickListener {void onItemClick(int position);
}public class LoopPagerAdapter extends PagerAdapter {private List<View> views;public LoopPagerAdapter(List<View> views) {this.views = views;}@Overridepublic int getCount() {//Integer.MAX_VALUE = 2147483647return Integer.MAX_VALUE;}@Overridepublic boolean isViewFromObject(View view, Object object) {return view == object;}@Overridepublic Object instantiateItem(ViewGroup container, int position) {if (views.size() > 0) {//position % view.size()是指虚拟的position会在[0,view.size())之间循环View view = views.get(position % views.size());if (container.equals(view.getParent())) {container.removeView(view);}container.addView(view);return view;}return null;}@Overridepublic void destroyItem(ViewGroup container, int position, Object object) {}
}public class FixedSpeedScroller extends Scroller {private int mDuration = 1000;public FixedSpeedScroller(Context context) {super(context);}public FixedSpeedScroller(Context context, Interpolator interpolator) {super(context, interpolator);}public FixedSpeedScroller(Context context, Interpolator interpolator, int duration) {this(context, interpolator);mDuration = duration;}@Overridepublic void startScroll(int startX, int startY, int dx, int dy, int duration) {// Ignore received duration, use fixed one insteadsuper.startScroll(startX, startY, dx, dy, mDuration);}@Overridepublic void startScroll(int startX, int startY, int dx, int dy) {// Ignore received duration, use fixed one insteadsuper.startScroll(startX, startY, dx, dy, mDuration);}
}

}
显示图片我用的是 脸书的加载方式 ,你可以自行更换。
2.下面这是自定义的样式文件:

3.布局XML代码 如下


记得xml布局文件上加上这句话
xmlns:app=”http://schemas.android.com/apk/res-auto”
标明支持自定义控件。
implements BannerLayout.OnBannerItemClickListener
给广告图添加监听事件 。

/* 图片地址*/
private List imgurls = new ArrayList();
添加图片
bannerLayout.setViewUrls(imgurls);

基本就这些 可以完美的实现 自动广告轮播。 麻蛋 我直接复制代码居然不显示 各位见谅, 有不明白的欢迎留言!

我们一起共同进步!表示谢谢!如果有技术问题欢迎

加入我的QQ群 285526158.

喜欢的可以关注微信公众号,哪里每天都会推荐一篇开源项目Git项目地址在里欢迎订阅

Android 自动广告轮播图相关推荐

  1. Android弧形广告图,简单封装弧形广告轮播图(ViewPager+贝塞尔曲线)

    前言 通过ViewPager和贝塞尔曲线实现了一个弧形广告轮播图. 效果图 弧形ViewPager 实现方法 想要实现这个效果,现在几行代码就可以了: Step 1. Add it in your r ...

  2. DEDE自动调用轮播图/幻灯片

    备注: 以下示例是以自动调取轮播图为例,具体使用时:步骤不变,内容据实调整即可 一.创建: 1.新建模型: 2.在新模型下依次添加字段: [本例字段:datu.xiaotu,分别给PC端和手机端用,据 ...

  3. Axure:实现跳转广告轮播图

    功能实现:当打开app时,显示app的广告轮播图  1.元件需求         三个图片.一个动态面板.三个动态模板的状态:state1.state2.state3 2.交互         将三个 ...

  4. android广告轮播图之匀速规律播放

    之前在电商项目中用到广告轮播的效果,在app端实现广告图片的上传,然后轮播图片,使用handler发送消息然后在handlemessage中在发消息的循环发送可以实现广告轮播效果,但是当添加图片以后, ...

  5. Android之无限轮播图源代码

    Android轮播广告图是大家经常用到的一个控件今天便撸了一把代码 实现步骤 使用Viewpager进行实现图片滑动 设置ViewPager的数据,让其无限切换 Activity代码 public c ...

  6. Android自定义控件之轮播图控件

    背景 最近要做一个轮播图的效果,网上看了几篇文章,基本上都能找到实现,效果还挺不错,但是在写的时候感觉每次都要单独去重新在Activity里写一堆代码.于是自己封装了一下.这里只是做了下封装成一个控件 ...

  7. 广告轮播图的前后台实现

    这个广告轮播系统是老师布置的前端实训的一个结课作业. 前端: 图片在广告位进行有时间性的轮播. 在两侧有前进和后退的操作. 在下面有几张轮播图的小框框,用来显示图片的进度, 点击小框框还可以立刻跳转到 ...

  8. Android Studio Banner轮播图

    Banner轮播图 使用步骤 代码片段 使用步骤 1.导依赖 2.写布局 3.图片集合(图片网址,图片资源id),标题集合 4.常用方法 图片集合 banner.setImages(imgs); 加载 ...

  9. java中广告维护轮播图怎么做_Banner广告轮播图

    需求描述 轮播图也是大部分app都有的效果,商品类跟新闻类的app是肯定会有的. 轮播图的效果跟第一次启动时的引导页类似,不过轮播图在引导页的基础上多了几个功能:在第一页也能向左滑动,在最后一页也能向 ...

最新文章

  1. 2021年大数据常用语言Scala(六):基础语法学习 数据类型与操作符
  2. verilog编译指令
  3. 推荐一款IDE开发工具插件GitToolBox
  4. 机器学习(MACHINE LEARNING)MATLAB非线性曲线拟合方法
  5. 如何在一小时内更新100篇文章?-Evernote Sync插件介绍
  6. Python应用实战-Python提升运行速度技巧总结
  7. 工作147:外部that
  8. Python List reverse()方法
  9. 遍历删除_面试难题:List 如何一边遍历,一边删除?
  10. -Block和JSON
  11. mysql 值到99999后不增值了_MySQL必知必会3
  12. STM32之通用定时器输出比较模式
  13. leetcode - 983. 最低票价
  14. Android开发网络连接超时
  15. Python_Python处理JSON文件
  16. android 编译打包pdf,Android使用iText生成pdf文件
  17. 二维码生成,打包下载zip,BigDecimal的取值和计算,java发送http请求
  18. clion小白使用技巧(持续更新中)
  19. 双向DC/DC变换器设计-硬件主拓扑
  20. 港科夜闻|香港科技大学(广州)(筹)校长倪明选教授在北京拜访国家教育部党组书记、部长怀进鹏...

热门文章

  1. 手机(Android)刷NetHunter安装指南,无需ssh执行kali命令, NetHunter支持的无线网卡列表!
  2. 聊一聊影响LCD屏背光效率的几个重要因素
  3. 微信小程序页面之间三种传值方式
  4. 开源简史基础:CNCF的诞生
  5. Btrace使用入门
  6. 前端兼容ie开发的注意事项
  7. python笔记 利用python 自动生成条形码 二维码
  8. javaFX登录注册GUI
  9. css换行,溢出显示省略号
  10. C++ - explicit关键字