目前市面上很多的app,在首页中都带有一个循环滚动,自动轮播的广告条,也就表明这个简单的控件是十分常用的,市面上有很多中实现方式,但基本上都是在自定义View中使用ViewPager来实现的,下面我们就来看下,具体的实现,其实很简单哦,无非就是自定义一个View。
- 创建布局文件BannerLayout.java
package cn.studyou.library.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import com.bumptech.glide.Glide;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import cn.studyou.library.R;
/**
* 基本功能:广告滚动条,支持自动轮播
* 创建:王杰
* 创建时间:16/3/13
* 邮箱:w489657152@gmail.com
*/
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;
private Shape indicatorShape = Shape.oval;
private int selectedIndicatorHeight = 6;
private int selectedIndicatorWidth = 6;
private int unSelectedIndicatorHeight = 6;
private int unSelectedIndicatorWidth = 6;
private Position indicatorPosition = Position.centerBottom;
private int autoPlayDuration = 4000;
private int scrollDuration = 900;
private int indicatorSpace = 3;
private int indicatorMargin = 10;
private int defaultImage;
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() {
@Override
public boolean handleMessage(Message msg) {
if (msg.what == WHAT_AUTO_PLAY) {
if (pager != null) {
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);
defaultImage = array.getResourceId(R.styleable.BannerLayoutStyle_defaultImage,defaultImage);
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<>();
itemCount = viewRes.size();
//主要是解决当item为小于3个的时候滑动有问题,这里将其拼凑成3个以上
if (itemCount < 1) {//当item个数0
throw new IllegalStateException("item count not equal zero");
} else if (itemCount < 2) {//当item个数为1
views.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个数为2
views.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);
}
@NonNull
private ImageView getImageView(Integer res, final int position) {
ImageView imageView = new ImageView(getContext());
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (onBannerItemClickListener != null) {
onBannerItemClickListener.onItemClick(position);
}
}
});
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Glide.with(getContext()).load(res).centerCrop().into(imageView);
return imageView;
}
//添加网络图片路径
public void setViewUrls(List<String> urls) {
List<View> views = new ArrayList<>();
itemCount = urls.size();
//主要是解决当item为小于3个的时候滑动有问题,这里将其拼凑成3个以上
if (itemCount < 1) {//当item个数0
throw new IllegalStateException("item count not equal zero");
} else if (itemCount < 2) { //当item个数为1
views.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个数为2
views.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);
}
@NonNull
private ImageView getImageView(String url, final int position) {
ImageView imageView = new ImageView(getContext());
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (onBannerItemClickListener != null) {
onBannerItemClickListener.onItemClick(position);
}
}
});
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
if (defaultImage != 0){
Glide.with(getContext()).load(url).placeholder(defaultImage).centerCrop().into(imageView);
}else {
Glide.with(getContext()).load(url).centerCrop().into(imageView);
}
return imageView;
}
//添加任意View视图
private void setViews(final List<View> views) {
//初始化pager
pager = new ViewPager(getContext());
//添加viewpager到SliderLayout
addView(pager);
setSliderTransformDuration(scrollDuration);
//初始化indicatorContainer
indicatorContainer = 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;
}
//设置margin
params.setMargins(indicatorMargin, indicatorMargin, indicatorMargin, indicatorMargin);
//添加指示器容器布局到SliderLayout
addView(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);
pager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public 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) {
e.printStackTrace();
}
}
/**
* 开始自动轮播
*/
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;
}
@Override
public int getCount() {
//Integer.MAX_VALUE = 2147483647
return Integer.MAX_VALUE;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public 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;
}
@Override
public 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;
}
@Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
// Ignore received duration, use fixed one instead
super.startScroll(startX, startY, dx, dy, mDuration);
}
@Override
public void startScroll(int startX, int startY, int dx, int dy) {
// Ignore received duration, use fixed one instead
super.startScroll(startX, startY, dx, dy, mDuration);
}
}
}
- 创建ViewPage指示器ViewPagerIndicator.java。
package cn.studyou.library.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import cn.studyou.library.R;
/**
* 基本功能:ViewPage指示器
* 创建:王杰
* 创建时间:16/3/13
* 邮箱:w489657152@gmail.com
*/
public class ViewPagerIndicator extends LinearLayout {
private Paint paint;
private Path path;
private int mTriangleWidth;
private int mTriangleHeight;
private static final float RADIO_TRIANGLE_WIDTH = 1 / 6F;
private final int DIMENSION_TRIANGLE_WIDTH_MAX = (int) (getScreenWidth() / 3 * RADIO_TRIANGLE_WIDTH);
private int mInitTranslationsX;
private int mTranslationsX;
private int mTabVisibleCount;
private static final int COUNT_DEFAULT_TAB = 4;
private static final int COLOR_TEXT_NORMAL = 0xFF2C2C2C;
private static final int COLOR_TEXT_HIGHLIGHT = 0xFF4CAF50;
private ViewPager mViewPager;
public PageChangeListener mListener;
private List<String> mTitles;
public ViewPagerIndicator(Context context) {
this(context, null);
}
public ViewPagerIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ViewPagerIndicator);
mTabVisibleCount = typedArray.getInt(R.styleable.ViewPagerIndicator_visible_tab_count, COUNT_DEFAULT_TAB);
if (mTabVisibleCount < 0) {
mTabVisibleCount = COUNT_DEFAULT_TAB;
}
typedArray.recycle();
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(COLOR_TEXT_HIGHLIGHT);
paint.setStyle(Paint.Style.FILL);
paint.setPathEffect(new CornerPathEffect(3));
}
@Override
protected void dispatchDraw(Canvas canvas) {
canvas.save();
canvas.translate(mInitTranslationsX + mTranslationsX, getHeight());
canvas.drawPath(path, paint);
canvas.restore();
super.dispatchDraw(canvas);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
int cCount = getChildCount();
if (cCount == 0)
return;
for (int i = 0; i < cCount; i++) {
View view = getChildAt(i);
LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
layoutParams.weight = 0;
layoutParams.width = getScreenWidth() / mTabVisibleCount;
view.setLayoutParams(layoutParams);
}
setItemClickEvent();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mTriangleWidth = (int) (w / mTabVisibleCount * RADIO_TRIANGLE_WIDTH);
mTriangleWidth = Math.min(mTriangleWidth, DIMENSION_TRIANGLE_WIDTH_MAX);
mInitTranslationsX = w / mTabVisibleCount / 2 - mTriangleWidth / 2;
initTriangle();
}
/**
* 初始化三角形
*/
private void initTriangle() {
mTriangleHeight = mTriangleWidth / 2;
path = new Path();
path.moveTo(0, 0);
path.lineTo(mTriangleWidth, 0);
path.lineTo(mTriangleWidth / 2, -mTriangleHeight);
path.close();
}
/**
* 指示器滚动
*
* @param position
* @param positionOffset
*/
public void scroll(int position, float positionOffset) {
int tabWidth = getWidth() / mTabVisibleCount;
mTranslationsX = (int) (tabWidth * (positionOffset + position));
//容器移动
if (getChildCount() > mTabVisibleCount && positionOffset > 0
&& position >= mTabVisibleCount - 1) {
this.scrollTo((int) ((position + 1 - mTabVisibleCount) * tabWidth + tabWidth * positionOffset)
, 0);
}
invalidate();
}
public int getScreenWidth() {
WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
}
public void setTabItemTitles(List<String> titles) {
if (titles != null && titles.size() > 0) {
this.removeAllViews();
mTitles = titles;
for (String title : mTitles) {
addView(generateTextView(title));
}
setItemClickEvent();
}
}
public void setVisibleTabCount(int count) {
mTabVisibleCount = count;
}
/**
* 根据title创建Tab
*
* @param title
* @return
*/
private View generateTextView(String title) {
TextView textView = new TextView(getContext());
LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = getScreenWidth() / mTabVisibleCount;
textView.setText(title);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
textView.setTextColor(COLOR_TEXT_NORMAL);
textView.setLayoutParams(layoutParams);
return textView;
}
public void setViewPager(ViewPager viewPager, int pos) {
mViewPager = viewPager;
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
scroll(position, positionOffset);
if (mListener != null) {
mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
@Override
public void onPageSelected(int position) {
if (mListener != null) {
mListener.onPageSelected(position);
}
highLightTextView(position);
}
@Override
public void onPageScrollStateChanged(int state) {
if (mListener != null) {
mListener.onPageScrollStateChanged(state);
}
}
});
mViewPager.setCurrentItem(pos);
highLightTextView(pos);
}
public interface PageChangeListener {
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);
public void onPageSelected(int position);
public void onPageScrollStateChanged(int state);
}
public void addOnPageChangeListener(PageChangeListener listener) {
this.mListener = listener;
}
/**
* 设置高亮文本
*
* @param pos
*/
private void highLightTextView(int pos) {
resetTextViewColor();
View view = getChildAt(pos);
if (view instanceof TextView) {
((TextView) view).setTextColor(COLOR_TEXT_HIGHLIGHT);
}
}
/**
* 重置颜色
*/
private void resetTextViewColor() {
for (int i = 0; i < getChildCount(); i++) {
View view = getChildAt(i);
if (view instanceof TextView) {
((TextView) view).setTextColor(COLOR_TEXT_NORMAL);
}
}
}
/**
* 设置Tab点击事件
*/
private void setItemClickEvent() {
int cCount = getChildCount();
for (int i = 0; i < cCount; i++) {
final int j = i;
View view = getChildAt(i);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mViewPager.setCurrentItem(j);
}
});
}
}
}
- 创建样式文件attr.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="visible_tab_count" format="integer"/>
<declare-styleable name="ViewPagerIndicator">
<attr name="visible_tab_count"/>
</declare-styleable>
<declare-styleable name="BannerLayoutStyle">
<attr name="selectedIndicatorColor" format="color|reference" />
<attr name="unSelectedIndicatorColor" format="color|reference" />
<attr name="indicatorShape" format="enum">
<enum name="rect" value="0" />
<enum name="oval" value="1" />
</attr>
<attr name="selectedIndicatorHeight" format="dimension|reference" />
<attr name="selectedIndicatorWidth" format="dimension|reference" />
<attr name="unSelectedIndicatorHeight" format="dimension|reference" />
<attr name="unSelectedIndicatorWidth" format="dimension|reference" />
<attr name="indicatorPosition" 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="indicatorSpace" format="dimension|reference" />
<attr name="indicatorMargin" format="dimension|reference" />
<attr name="autoPlayDuration" format="integer|reference" />
<attr name="scrollDuration" format="integer|reference" />
<attr name="isAutoPlay" format="boolean"/>
<attr name="defaultImage" format="integer|reference"/>
</declare-styleable>
</resources>
- 在Activity中使用这个控件,首先在布局文件中添加次控件,然后在Activity中,绑定数据即可,对于Fragment也是一样的操作。
- 如MainActivity的布局文件activity_main.xml中添加如下代码:
<cn.studyou.library.view.BannerLayout
android:id="@+id/banner"
android:layout_width="match_parent"
android:layout_height="180dp"
app:autoPlayDuration="8000"
app:defaultImage="@mipmap/ic_launcher"
app:indicatorMargin="10dp"
app:indicatorPosition="rightBottom"
app:indicatorShape="oval"
app:indicatorSpace="2dp"
app:scrollDuration="1100"
app:selectedIndicatorColor="?attr/colorPrimary"
app:selectedIndicatorHeight="6dp"
app:selectedIndicatorWidth="6dp"
app:unSelectedIndicatorColor="#99ffffff"
app:unSelectedIndicatorHeight="6dp"
app:unSelectedIndicatorWidth="6dp" />
- MainActivity代码如下:
package cn.studyou.autoscrollbanner;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import cn.studyou.library.view.BannerLayout;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<String> urls = new ArrayList<>();
urls.add("http://a.hiphotos.baidu.com/image/pic/item/b3fb43166d224f4a58fcfc540ef790529822d114.jpg");
urls.add("http://att2.citysbs.com/hangzhou/sns01/forum/2010/10/09-10/20101009_42172338386c23dddb03zQ695asbeKu4.jpg");
urls.add("http://e.hiphotos.baidu.com/image/pic/item/14ce36d3d539b600be63e95eed50352ac75cb7ae.jpg");
urls.add("http://f.hiphotos.baidu.com/image/pic/item/242dd42a2834349b7eaf886ccdea15ce37d3beaa.jpg");
urls.add("http://b.hiphotos.baidu.com/image/pic/item/9922720e0cf3d7ca021ac950f71fbe096b63a92c.jpg");
BannerLayout banner = (BannerLayout) findViewById(R.id.banner);
//网络地址
banner.setViewUrls(urls);
//本地资源
// banner.setViewRes(viewRes);
//添加点击监听
banner.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
@Override
public void onItemClick(int position) {
// Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
}
}
- 到这里一个可循环滚动,自动轮播的广告条就完成了,运行项目就可看到效果。
- 项目github地址:https://github.com/wjie2014/AutoScrollBanner
- 效果图如下:
网友评论