温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Android应用中实现一个无限循环轮播

发布时间:2020-12-02 15:12:44 来源:亿速云 阅读:220 作者:Leah 栏目:移动开发

如何在Android应用中实现一个无限循环轮播?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

一、自定义控件属性

新建自定义控件SliderLayout继承于RelativeLayout,首先要考虑的就是自定义的控件需要扩展那些属性,把这些属性列出来。在这里是要实现类似于京东淘宝的无限轮播广告栏,那么首先想到的就是轮播的时长、轮播指示器的样式等等。我在这里列举了一些并且结合到了代码中。

1、扩展属性

(1)是否开启自动轮播的功能。
(2)指示器的图形样式,一般为圆形和方形两种。
(3)指示器的位置,一般为底部或者顶部。
(4)指示器被选中和不被选中时的样式:颜色、高度、宽度、间隔等。
(5)轮播的时长。
(6)加载的如果是网络图片的话,需要默认图片和错误图片等。

2、在attrs.xml文件中添加这些扩展的属性。

<declare-styleable name="SliderLayout">
  <attr name="sl_is_auto_play" format="boolean"/>
  <attr name="sl_indicator_shape" format="enum">
   <enum name="oval" value="0" />
   <enum name="rect" value="1" />
  </attr>
  <attr name="sl_indicator_position" format="enum">
   <enum name="centerBottom" value="0" />
   <enum name="rightBottom" value="1" />
   <enum name="leftBottom" value="2" />
   <enum name="centerTop" value="3" />
   <enum name="rightTop" value="4" />
   <enum name="leftTop" value="5" />
  </attr>
  <attr name="sl_selected_indicator_color" format="color|reference" />
  <attr name="sl_unselected_indicator_color" format="color|reference" />
  <attr name="sl_selected_indicator_height" format="dimension|reference" />
  <attr name="sl_selected_indicator_width" format="dimension|reference" />
  <attr name="sl_unselected_indicator_height" format="dimension|reference" />
  <attr name="sl_unselected_indicator_width" format="dimension|reference" />
  <attr name="sl_indicator_space" format="dimension|reference" />
  <attr name="sl_indicator_margin" format="dimension|reference" />
  <attr name="sl_auto_play_duration" format="integer|reference" />
  <attr name="sl_default_image" format="reference"/>
  <attr name="sl_error_image" format="reference"/>
 </declare-styleable>

二、自定义轮播控件的初始化

1、获取到扩展属性的值

在自定义SliderLayout中获取到扩展的样式,然后根据样式获取相应的属性值,最好是要先设置好默认值。

TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.SliderLayout, defStyleAttr, 0);
  if (array != null) {
   isAutoPlay = array.getBoolean(R.styleable.SliderLayout_sl_is_auto_play, isAutoPlay);
   //get the shape of indicator
   int intShape = array.getInt(R.styleable.SliderLayout_sl_indicator_shape, indicatorShape.ordinal());
   for (IndicatorShape shape : IndicatorShape.values()) {
    if (shape.ordinal() == intShape) {
     indicatorShape = shape;
     break;
    }
   }
   //get the position of indicator
   int intPosition = array.getInt(R.styleable.SliderLayout_sl_indicator_position, IndicatorPosition.centerBottom.ordinal());
   for (IndicatorPosition position : IndicatorPosition.values()) {
    if (position.ordinal() == intPosition) {
     indicatorPosition = position;
     break;
    }
   }
   unSelectedIndicatorColor = array.getColor(R.styleable.SliderLayout_sl_unselected_indicator_color, unSelectedIndicatorColor);
   selectedIndicatorColor = array.getColor(R.styleable.SliderLayout_sl_selected_indicator_color, selectedIndicatorColor);
   unSelectedIndicatorHeight = array.getDimension(R.styleable.SliderLayout_sl_unselected_indicator_height, unSelectedIndicatorHeight);
   unSelectedIndicatorWidth = array.getDimension(R.styleable.SliderLayout_sl_unselected_indicator_width, unSelectedIndicatorWidth);
   selectedIndicatorHeight = array.getDimension(R.styleable.SliderLayout_sl_selected_indicator_height, selectedIndicatorHeight);
   selectedIndicatorWidth = array.getDimension(R.styleable.SliderLayout_sl_selected_indicator_width, selectedIndicatorWidth);
   indicatorSpace = array.getDimension(R.styleable.SliderLayout_sl_indicator_space, indicatorSpace);
   indicatorMargin = array.getDimension(R.styleable.SliderLayout_sl_indicator_margin, indicatorMargin);
   autoPlayDuration = array.getInt(R.styleable.SliderLayout_sl_auto_play_duration, autoPlayDuration);
   defaultImage = array.getResourceId(R.styleable.SliderLayout_sl_default_image, defaultImage);
   errorImage = array.getResourceId(R.styleable.SliderLayout_sl_error_image, errorImage);
  }

2、初始化控件

根据这里所需要实现的功能,首先需要一个图像切换器ImageSwticher,还要指示器,这里就用ImageView了。

switcherImage = new ImageSwitcher(context);
  switcherImage.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
for (int i = 0; i < itemCount; i++) {
   ImageView indicator = new ImageView(context);
   indicator.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
   indicator.setPadding((int) (indicatorSpace), (int) (indicatorSpace), (int) (indicatorSpace), (int) (indicatorSpace));
   indicator.setImageDrawable(unSelectedDrawable);
   indicatorContainer.addView(indicator);
   final int finalI = i;
   indicator.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
     stopAutoPlay();
     switchIndicator(finalI);
     pictureIndex = finalI;
     handler.sendEmptyMessageDelayed(START_AUTO_PLAY,autoPlayDuration);
    }
   });
  }

3、初始化选中第一张图片

专门写一个针对指示器切换的函数,然后在初始化的时候直接调用,选中第一个指示器,就是选中第一张图片了。

函数代码如下。

private void switchIndicator(int index) {
  for (int i = 0; i < indicatorContainer.getChildCount(); i++) {
   ((ImageView) indicatorContainer.getChildAt(i)).setImageDrawable(i == index &#63; selectedDrawable : unSelectedDrawable);
  }
  loadImage(index);
 }

调用选中第一张图。

switchIndicator(0);

三、图片的加载

1、网路图片的加载

在这里使用Picasso框架来加载图片,根据url来加载显示图片,同时也要显示图片的加载进度,这里就需要一个Dialog提示框了,Dialog的样式最好是可以自定义的。

private void loadNetImage(int pictureIndex) {
  if (list != null && list.size() != 0) {
   Picasso.with(context)
     .load((String) list.get(pictureIndex))
     .placeholder(defaultImage)
     .error(errorImage)
     .tag(context)
     .into(mTarget);
  }
 }

下面是图片的加载提示过程。

private Target mTarget = new Target() {
  @Override
  public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
   dismissDialog();
   ((ImageView) switcherImage.getCurrentView()).setScaleType(ImageView.ScaleType.CENTER_CROP);
   ((ImageView) switcherImage.getCurrentView()).setLayoutParams(new ImageSwitcher.LayoutParams(ImageSwitcher.LayoutParams.MATCH_PARENT, ImageSwitcher.LayoutParams.MATCH_PARENT));
   ((ImageView) switcherImage.getCurrentView()).setImageBitmap(bitmap);
  }
  @Override
  public void onBitmapFailed(Drawable errorDrawable) {
   dismissDialog();
   ((ImageView) switcherImage.getCurrentView()).setImageDrawable(errorDrawable);
  }
  @Override
  public void onPrepareLoad(Drawable placeHolderDrawable) {
   showDialog();
  }
 };

2、资源图片的加载

只能加载网络图片是不够的呢,还需要可以加载资源图片,加载资源图片的办法就更加简单了。

private void loadFileImage(int pictureIndex) {
   if (list != null && list.size() != 0) {
    switcherImage.setImageResource((Integer) list.get(pictureIndex));
   }
  }

四、设置图片切换的动画

设置图片从左往右以及从右往左的动画效果,并且当滑动到该图片时,指示器也要一起变化,这里就简单说下从左往右的动画了。

private void SliderLeftToRight() {
  // get current index
  pictureIndex = pictureIndex == 0 &#63; itemCount - 1
    : pictureIndex - 1;
  // set Animation
  switcherImage.setInAnimation(AnimationUtils.loadAnimation(context,
    android.R.anim.slide_in_left));
  switcherImage.setOutAnimation(AnimationUtils.loadAnimation(context,
    android.R.anim.slide_out_right));
  switchIndicator(pictureIndex);
 }

从右往左滑动时的代码和这个是一样的,就是换了下方向,需要自己定义下。

五、定义图片的点击事件

1、定义interface来监听事件

在自定义控件中自定义一个interface来监听事件就可以了。

public interface IOnClickListener {
  void onItemClick(View view, int position);
 }

2、在onTouch中调用点击事件。

这里需要说明下为什么在onTouch中处理,因为onTouch是触摸事件,在滑动的过程中,用户是触摸了屏幕的,所以根据用户触摸屏幕时点击下的X坐标和点击起来时的X坐标的对比来判断是左滑还是右滑了,这样的话,就会和onClick事件相冲了,所以就想到了一个办法,那就是在范围内的话,就默认为点击事件,范围外就是滑动事件了。

if (0==(Math.abs(touchUpX - touchDownX))||(Math.abs(touchUpX - touchDownX))<50) {
    if (listener != null) {
     stopAutoPlay();
     listener.onItemClick(view, pictureIndex);
     handler.sendEmptyMessageDelayed(START_AUTO_PLAY,autoPlayDuration);
    }
}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI