//轮播图控件
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);
}
}
});