高效可点击的轮播图

//轮播图控件

packagecn.mohekeji.xiangshan.common.widget;

importandroid.content.Context;

importandroid.content.res.TypedArray;

importandroid.graphics.drawable.Drawable;

importandroid.graphics.drawable.GradientDrawable;

importandroid.graphics.drawable.LayerDrawable;

importandroid.os.Handler;

importandroid.os.Message;

importandroid.support.annotation.NonNull;

importandroid.support.v4.view.PagerAdapter;

importandroid.support.v4.view.ViewPager;

importandroid.util.AttributeSet;

importandroid.view.Gravity;

importandroid.view.MotionEvent;

importandroid.view.View;

importandroid.view.ViewGroup;

importandroid.view.animation.Interpolator;

importandroid.widget.ImageView;

importandroid.widget.LinearLayout;

importandroid.widget.RelativeLayout;

importandroid.widget.Scroller;

importjava.lang.reflect.Field;

importjava.util.ArrayList;

importjava.util.List;

importcn.mohekeji.xiangshan.R;

importcn.mohekeji.xiangshan.common.net.VolleyManager;

/**

* Created by Apple on 16/7/6.

*/

public classBannerLayoutextendsRelativeLayout {

privateViewPagerpager;

//指示器容器

privateLinearLayoutindicatorContainer;

privateDrawableunSelectedDrawable;

privateDrawableselectedDrawable;

private intWHAT_AUTO_PLAY=1000;

private booleanisAutoPlay=true;

private intitemCount;

private intselectedIndicatorColor=0xffff0000;

private intunSelectedIndicatorColor=0x88888888;

privateShapeindicatorShape= Shape.oval;

private intselectedIndicatorHeight=6;

private intselectedIndicatorWidth=6;

private intunSelectedIndicatorHeight=6;

private intunSelectedIndicatorWidth=6;

privatePositionindicatorPosition= Position.centerBottom;

private intautoPlayDuration=4000;

private intscrollDuration=900;

private intindicatorSpace=3;

private intindicatorMargin=10;

private intdefaultImage;

private enumShape {

rect,oval

}

private enumPosition {

centerBottom,

rightBottom,

leftBottom,

centerTop,

rightTop,

leftTop

}

privateOnBannerItemClickListeneronBannerItemClickListener;

privateHandlerhandler=newHandler(newHandler.Callback() {

@Override

public booleanhandleMessage(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;

}

});

publicBannerLayout(Context context) {

super(context);

init(null,0);

}

publicBannerLayout(Context context, AttributeSet attrs) {

super(context, attrs);

init(attrs,0);

}

publicBannerLayout(Context context, AttributeSet attrs,intdefStyleAttr) {

super(context, attrs, defStyleAttr);

init(attrs, defStyleAttr);

}

private voidinit(AttributeSet attrs,intdefStyle) {

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);

intshape = 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);

intposition = 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 =newGradientDrawable();

//绘制选中状态图形

GradientDrawable selectedGradientDrawable;

selectedGradientDrawable =newGradientDrawable();

switch(indicatorShape) {

caserect:

unSelectedGradientDrawable.setShape(GradientDrawable.RECTANGLE);

selectedGradientDrawable.setShape(GradientDrawable.RECTANGLE);

break;

caseoval:

unSelectedGradientDrawable.setShape(GradientDrawable.OVAL);

selectedGradientDrawable.setShape(GradientDrawable.OVAL);

break;

}

unSelectedGradientDrawable.setColor(unSelectedIndicatorColor);

unSelectedGradientDrawable.setSize(unSelectedIndicatorWidth,unSelectedIndicatorHeight);

unSelectedLayerDrawable =newLayerDrawable(newDrawable[]{unSelectedGradientDrawable});

unSelectedDrawable= unSelectedLayerDrawable;

selectedGradientDrawable.setColor(selectedIndicatorColor);

selectedGradientDrawable.setSize(selectedIndicatorWidth,selectedIndicatorHeight);

selectedLayerDrawable =newLayerDrawable(newDrawable[]{selectedGradientDrawable});

selectedDrawable= selectedLayerDrawable;

}

//添加本地图片路径

public voidsetViewRes(List viewRes) {

List views =newArrayList<>();

itemCount= viewRes.size();

//主要是解决当item为小于3个的时候滑动有问题,这里将其拼凑成3个以上

if(itemCount<1) {//当item个数0

throw newIllegalStateException("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(inti =0; i < viewRes.size(); i++) {

views.add(getImageView(viewRes.get(i), i));

}

}

setViews(views);

}

@NonNull

privateImageView getImageView(Integer res,final intposition) {

ImageView imageView =newImageView(getContext());

imageView.setOnClickListener(newOnClickListener() {

@Override

public voidonClick(View v) {

if(onBannerItemClickListener!=null) {

onBannerItemClickListener.onItemClick(position);

}

}

});

imageView.setScaleType(ImageView.ScaleType.FIT_XY);

VolleyManager.getInstance().loadImage(res.toString(), imageView);

returnimageView;

}

//添加网络图片路径

public voidsetViewUrls(List urls) {

List views =newArrayList<>();

itemCount= urls.size();

//主要是解决当item为小于3个的时候滑动有问题,这里将其拼凑成3个以上

if(itemCount<1) {//当item个数0

throw newIllegalStateException("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(inti =0; i < urls.size(); i++) {

views.add(getImageView(urls.get(i), i));

}

}

setViews(views);

}

@NonNull

privateImageView getImageView(String url,final intposition) {

ImageView imageView =newImageView(getContext());

imageView.setScaleType(ImageView.ScaleType.FIT_XY);

imageView.setOnClickListener(newOnClickListener() {

@Override

public voidonClick(View v) {

if(onBannerItemClickListener!=null) {

onBannerItemClickListener.onItemClick(position);

}

}

});

imageView.setScaleType(ImageView.ScaleType.FIT_XY);

if(defaultImage!=0) {

VolleyManager.getInstance().loadImage(url.toString(), imageView);

}else{

VolleyManager.getInstance().loadImage(url.toString(), imageView);

}

returnimageView;

}

//添加任意View视图

private voidsetViews(finalList views) {

//初始化pager

pager=newViewPager(getContext());

//添加viewpager到SliderLayout

addView(pager);

setSliderTransformDuration(scrollDuration);

//初始化indicatorContainer

indicatorContainer=newLinearLayout(getContext());

indicatorContainer.setGravity(Gravity.CENTER_VERTICAL);

RelativeLayout.LayoutParams params =newLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

switch(indicatorPosition) {

casecenterBottom:

params.addRule(RelativeLayout.CENTER_HORIZONTAL);

params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

break;

casecenterTop:

params.addRule(RelativeLayout.CENTER_HORIZONTAL);

params.addRule(RelativeLayout.ALIGN_PARENT_TOP);

break;

caseleftBottom:

params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

break;

caseleftTop:

params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

params.addRule(RelativeLayout.ALIGN_PARENT_TOP);

break;

caserightBottom:

params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

break;

caserightTop:

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(inti =0; i

ImageView indicator =newImageView(getContext());

indicator.setLayoutParams(newViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

indicator.setPadding(indicatorSpace,indicatorSpace,indicatorSpace,indicatorSpace);

indicator.setImageDrawable(unSelectedDrawable);

indicatorContainer.addView(indicator);

}

LoopPagerAdapter pagerAdapter =newLoopPagerAdapter(views);

pager.setAdapter(pagerAdapter);

//设置当前item到Integer.MAX_VALUE中间的一个值,看起来像无论是往前滑还是往后滑都是ok的

//如果不设置,用户往左边滑动的时候已经划不动了

inttargetItemPosition = Integer.MAX_VALUE/2- Integer.MAX_VALUE/2%itemCount;

pager.setCurrentItem(targetItemPosition);

switchIndicator(targetItemPosition %itemCount);

pager.addOnPageChangeListener(newViewPager.SimpleOnPageChangeListener() {

@Override

public voidonPageSelected(intposition) {

switchIndicator(position %itemCount);

}

});

startAutoPlay();

}

public voidsetSliderTransformDuration(intduration) {

try{

Field mScroller = ViewPager.class.getDeclaredField("mScroller");

mScroller.setAccessible(true);

FixedSpeedScroller scroller =newFixedSpeedScroller(pager.getContext(),null, duration);

mScroller.set(pager, scroller);

}catch(Exception e) {

e.printStackTrace();

}

}

/**

* 开始自动轮播

*/

public voidstartAutoPlay() {

stopAutoPlay();// 避免重复消息

if(isAutoPlay) {

handler.sendEmptyMessageDelayed(WHAT_AUTO_PLAY,autoPlayDuration);

}

}

@Override

protected voidonWindowVisibilityChanged(intvisibility) {

super.onWindowVisibilityChanged(visibility);

if(visibility ==VISIBLE) {

startAutoPlay();

}else{

stopAutoPlay();

}

}

/**

* 停止自动轮播

*/

public voidstopAutoPlay() {

if(isAutoPlay) {

handler.removeMessages(WHAT_AUTO_PLAY);

}

}

@Override

public booleandispatchTouchEvent(MotionEvent ev) {

switch(ev.getAction()) {

caseMotionEvent.ACTION_DOWN:

stopAutoPlay();

break;

caseMotionEvent.ACTION_CANCEL:

caseMotionEvent.ACTION_UP:

startAutoPlay();

break;

}

return super.dispatchTouchEvent(ev);

}

/**

* 切换指示器状态

*

*@paramcurrentPosition当前位置

*/

private voidswitchIndicator(intcurrentPosition) {

for(inti =0; i

((ImageView)indicatorContainer.getChildAt(i)).setImageDrawable(i == currentPosition ?selectedDrawable:unSelectedDrawable);

}

}

public voidsetOnBannerItemClickListener(OnBannerItemClickListener onBannerItemClickListener) {

this.onBannerItemClickListener= onBannerItemClickListener;

}

public interfaceOnBannerItemClickListener {

voidonItemClick(intposition);

}

public classLoopPagerAdapterextendsPagerAdapter {

privateListviews;

publicLoopPagerAdapter(List views) {

this.views= views;

}

@Override

public intgetCount() {

//Integer.MAX_VALUE = 2147483647

returnInteger.MAX_VALUE;

}

@Override

public booleanisViewFromObject(View view, Object object) {

returnview == object;

}

@Override

publicObject instantiateItem(ViewGroup container,intposition) {

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);

returnview;

}

return null;

}

@Override

public voiddestroyItem(ViewGroup container,intposition, Object object) {

}

}

public classFixedSpeedScrollerextendsScroller {

private intmDuration=1000;

publicFixedSpeedScroller(Context context) {

super(context);

}

publicFixedSpeedScroller(Context context, Interpolator interpolator) {

super(context, interpolator);

}

publicFixedSpeedScroller(Context context, Interpolator interpolator,intduration) {

this(context, interpolator);

mDuration= duration;

}

@Override

public voidstartScroll(intstartX,intstartY,intdx,intdy,intduration) {

// Ignore received duration, use fixed one instead

super.startScroll(startX, startY, dx, dy,mDuration);

}

@Override

public voidstartScroll(intstartX,intstartY,intdx,intdy) {

// Ignore received duration, use fixed one instead

super.startScroll(startX, startY, dx, dy,mDuration);

}

}

}

//放置图片URL的集合

privateArrayListimagesList;

//放置图片

BannerLayoutbanner;

viewFlow2.setViewUrls(imageList);

//点击事件

banner.setOnBannerItemClickListener(newBannerLayout.OnBannerItemClickListener() {

@Override

public voidonItemClick(intposition) {

RecommendArticalDetailData recommendArticalDetailData = (RecommendArticalDetailData)recommend.get(position);

String ImagesType=recommendArticalDetailData.getType();

if(ImagesType.equals("0")){

Intent intent =newIntent(getActivity(), HealthyInforDetailActivity.class);

intent.putExtra("scienceId", recommendArticalDetailData.getScienceId());

intent.putExtra("thumbUrl", recommendArticalDetailData.getRecommendThumbnailUrl());

getActivity().startActivity(intent);

}else{

Intent intent =newIntent(getActivity(), LineCourseDetailActivity.class);

intent.putExtra("curriculumId", recommendArticalDetailData.getScienceId());

getActivity().startActivity(intent);

}

}

});

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,542评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,596评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,021评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,682评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,792评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,985评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,107评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,845评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,299评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,612评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,747评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,441评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,072评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,828评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,069评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,545评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,658评论 2 350

推荐阅读更多精彩内容