很多同学在开发过程中需要添加轮播图等,我浏览了网上很多轮播图实现方式,大多数不够完美。
这是一个基于viewpager的轮播图,注意使用的时候要给图片做缓存等,以避免图片的oom。
package com.base.add;
import java.util.ArrayList;
import java.util.List;
import com.base.ActBase;
import com.shennongshi.dingdong.R;
import com.shennongshi.dingdong.entity.ElunboImg;
import com.shennongshi.dingdong.ui.zhuye.ViewPagerYGesture;
import com.third.imageloader.ImageFetcher;
import com.utils.widget.HandlerWeak;
import android.app.Activity;
import android.content.Context;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
/**
* 实现可循环,可轮播的viewpager
*/
public class CycleViewPager extends RelativeLayout implements OnPageChangeListener {
private int time = 5000;
private static final int WHEEL = 100; // 转动
private static final int WHEEL_WAIT = 101; // 等待
private long releaseTime = 0; // 手指松开、页面不滚动时间,防止手机松开后短时间进行切换
private int currentPosition = 0; // 轮播当前位置
private boolean isScrolling = false; // 滚动框是否滚动着
private boolean isCycle = false; // 是否循环
private boolean isWheel = false; // 是否轮播
private List<ImageView> imageViews = new ArrayList<ImageView>();
private ImageView[] indicators;
private LinearLayout indicatorLayout; // 指示器
private ViewPagerYGesture viewPager;
private ViewPagerAdapter adapter;
private ImageCycleViewListener mImageCycleViewListener;
private HandlerWeak handler = new HandlerWeak((Context) getContext()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == WHEEL && imageViews.size() != 0) {
if (!isScrolling) {
int max = imageViews.size() + 1;
int position = (currentPosition + 1) % imageViews.size();
viewPager.setCurrentItem(position, true);
if (position == max) { // 最后一页时回到第一页
viewPager.setCurrentItem(1, false);
}
}
releaseTime = System.currentTimeMillis();
handler.removeCallbacks(runnable);
handler.postDelayed(runnable, time);
}
else if (msg.what == WHEEL_WAIT && imageViews.size() != 0) {
handler.removeCallbacks(runnable);
handler.postDelayed(runnable, time);
}
}
};
public CycleViewPager(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView();
}
public CycleViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public CycleViewPager(Context context) {
super(context);
initView();
}
private void initView() {
getContext();
inflate(getContext(), R.layout.view_cycle_viewpager_contet, this);
viewPager = (ViewPagerYGesture) findViewById(R.id.viewPager);
indicatorLayout = (LinearLayout)findViewById(R.id.layout_viewpager_indicator);
}
public void setData(List<ImageView> views, ImageCycleViewListener listener) {
setData(views, listener, 0);
}
/**
* 初始化viewpager
*
* @param views
* 要显示的views
* @param showPosition
* 默认显示位置
*/
public void setData(List<ImageView> views, ImageCycleViewListener listener, int showPosition) {
mImageCycleViewListener = listener;
this.imageViews.clear();
if (views.size() == 0) {
return;
}
for (ImageView item : views) {
this.imageViews.add(item);
}
int ivSize = views.size();
if (ivSize > 1) {
if (isCycle) indicators = new ImageView[ivSize - 2];
else indicators = new ImageView[ivSize];
indicatorLayout.removeAllViews();
for (int i = 0; i < indicators.length; i++) {
View view = LayoutInflater.from(getContext()).inflate(
R.layout.view_cycle_viewpager_indicator, null);
indicators[i] = (ImageView) view.findViewById(R.id.image_indicator);
indicatorLayout.addView(view);
}
}
adapter = new ViewPagerAdapter();
// 默认指向第一项,下方viewPager.setCurrentItem将触发重新计算指示器指向
setIndicator(0);
viewPager.setOnPageChangeListener(this);
viewPager.setAdapter(adapter);
if (showPosition < 0 || showPosition >= views.size())
showPosition = 0;
if (isCycle) {
showPosition = showPosition + 1;
}
viewPager.setCurrentItem(showPosition);
}
/**
* 设置指示器居中,默认指示器在右方
*/
public void setIndicatorCenter() {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
indicatorLayout.setLayoutParams(params);
}
/**
* 是否循环,默认不开启,开启前,请将views的最前面与最后面各加入一个视图,用于循环
*
* @param isCycle
* 是否循环
*/
public void setCycle(boolean isCycle) {
this.isCycle = isCycle;
}
/**
* 是否处于循环状态
*
* @return
*/
public boolean isCycle() {
return isCycle;
}
/**
* 设置是否轮播,默认不轮播,轮播一定是循环的
*
* @param isWheel
*/
public void setWheel(boolean isWheel) {
this.isWheel = isWheel;
isCycle = true;
if (isWheel) {
handler.postDelayed(runnable, time);
}
}
/**
* 是否处于轮播状态
*
* @return
*/
public boolean isWheel() {
return isWheel;
}
final Runnable runnable = new Runnable() {
@Override
public void run() {
if (getContext() != null && !((Activity) getContext()).isFinishing() && isWheel) {
long now = System.currentTimeMillis();
// 检测上一次滑动时间与本次之间是否有触击(手滑动)操作,有的话等待下次轮播
if (now - releaseTime > time - 500) {
handler.sendEmptyMessage(WHEEL);
} else {
handler.sendEmptyMessage(WHEEL_WAIT);
}
}
}
};
/**
* 释放指示器高度,可能由于之前指示器被限制了高度,此处释放
*/
public void releaseHeight() {
this.getLayoutParams().height = RelativeLayout.LayoutParams.MATCH_PARENT;
refreshData();
}
/**
* 设置轮播暂停时间,即没多少秒切换到下一张视图.默认5000ms
*
* @param time
* 毫秒为单位
*/
public void setTime(int time) {
this.time = time;
}
/**
* 刷新数据,当外部视图更新后,通知刷新数据
*/
public void refreshData() {
if (adapter != null) adapter.notifyDataSetChanged();
}
/**
* 页面适配器 返回对应的view
*
* @author Yuedong Li
*
*/
private class ViewPagerAdapter extends PagerAdapter {
@Override
public int getCount() {
return imageViews.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public View instantiateItem(ViewGroup container, final int position) {
ImageView v = imageViews.get(position);
if (mImageCycleViewListener != null) {
v.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mImageCycleViewListener.onImageClick(v);
}
});
}
ElunboImg tag = (ElunboImg) v.getTag();
ImageFetcher imageFetcher = ((ActBase) getContext()).getImageFetcher();
// imageFetcher.setImageSize(ActBase.MIN_WIDTH);
imageFetcher.setImageSize(512);
imageFetcher.setLoadingImage(null);
imageFetcher.loadImage(tag.getImage(), v);
// Glide.with(getContext()).load(tag.getImage()).diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.drawable.default_big).into(v);
container.addView(v);
return v;
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
@Override
public void onPageScrollStateChanged(int arg0) {
if (arg0 == 1) { // viewPager在滚动
isScrolling = true;
return;
} else if (arg0 == 0) { // viewPager滚动结束
releaseTime = System.currentTimeMillis();
viewPager.setCurrentItem(currentPosition, false);
}
isScrolling = false;
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int arg0) {
int max = imageViews.size() - 1;
int position = arg0;
currentPosition = arg0;
if (isCycle) {
if (arg0 == 0) {
currentPosition = max - 1;
} else if (arg0 == max) {
currentPosition = 1;
}
position = currentPosition - 1;
}
setIndicator(position);
}
/**
* 返回当前位置,循环时需要注意返回的position包含之前在views最前方与最后方加入的视图,即当前页面试图在views集合的位置
*
* @return
*/
public int getCurrentPostion() {
return currentPosition;
}
/**
* 设置指示器
*
* @param postion 默认指示器位置
*/
private void setIndicator(int postion) {
if (indicators == null) return;
int length = indicators.length;
for (int i = 0; i < length; i++) {
indicators[i].setBackgroundResource(R.drawable.shape_yuandian_white40);
}
if (length > postion) {
indicators[postion].setBackgroundResource(R.drawable.shape_yuandian_white100);
}
}
/**
* 轮播控件的监听事件
*
* @author minking
*/
public static interface ImageCycleViewListener {
/**
* 单击图片事件
*
* @param positionweek
* @param imageView
*/
public void onImageClick(View imageView);
}
}
使用方式举例:
首先在xml文件中定义,然后在java代码中引用。
package com.shennongshi.dingdong.ui.xuewen.liebiao;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import com.base.ActGuide;
import com.base.GetDataManager;
import com.base.IVolleyResponse;
import com.base.add.CycleViewPager;
import com.base.add.CycleViewPager.ImageCycleViewListener;
import com.shennongshi.dingdong.R;
import com.shennongshi.dingdong.entity.Elunbo;
import com.shennongshi.dingdong.entity.ElunboImg;
import com.shennongshi.dingdong.pztools.IntentConstant;
import com.shennongshi.dingdong.pztools.PreferenceKey;
import com.shennongshi.dingdong.pztools.Urls.POST;
import com.utils.db.ConfigPreferences;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FragHeaderHYZX extends LinearLayout {
private CycleViewPager lunboImage_vp;
// private EditText shuru;
// private TextView sousuo;
private List<ImageView> mViews = new ArrayList<ImageView>();
private String sid;
public FragHeaderHYZX(Context context) {
super(context);
initContainerView();
sid = ConfigPreferences.getString(PreferenceKey.Sid, "");
requestgetFocusImages();
}
private void initContainerView() {
inflate(getContext() , R.layout.frag_header_hyzx , this);
lunboImage_vp = (CycleViewPager) findViewById(R.id.lunboImage_vp);
// shuru = (EditText) findViewById(R.id.zixun_query);
// sousuo = (TextView) findViewById(R.id.zixun_sousuotv);
// sousuo.setOnClickListener(sousuolistener);
}
// private OnClickListener sousuolistener = new OnClickListener() {
// @Override
// public void onClick(View v) {
// Bundle bundle = new Bundle();
// bundle.putString(IntentConstant.SEARCHTEXT,shuru.getText().toString());
// ActGuide.goBundle(getContext(),bundle, ActGuide.FRAG_ZXSearch);
// }
// };
public void requestgetFocusImages() {
JSONObject jsonP = new JSONObject();
try {
jsonP.put("sid", sid);
} catch (JSONException e) {
e.printStackTrace();
}
GetDataManager.post(POST.GETFOCUSIMAGES, jsonP, Elunbo.class,
new IVolleyResponse<Elunbo>() {
@Override
public void onResponse(Elunbo response) {
Elunbo elunbo = response;
List<ElunboImg> imgList = elunbo.getImage_list();
initialize(imgList);
}
});
}
private void initialize(List<ElunboImg> imgList) {
if (imgList == null || imgList.isEmpty()) return;
int size = imgList.size();
mViews.clear();
for (int i = 0; i < size; i++) {
mViews.add(getImageView(getContext(), imgList.get(i)));
}
if (size == 1) lunboImage_vp.setCycle(false);
else {
lunboImage_vp.setTime(5000);
lunboImage_vp.setWheel(true);
mViews.add(0, getImageView(getContext(), imgList.get(size - 1)));
mViews.add(getImageView(getContext(), imgList.get(0)));
}
LunboListenter lunboListenter = new LunboListenter();
lunboImage_vp.setData(mViews, lunboListenter);
// lunboImage_vp.setIndicatorCenter();
}
private class LunboListenter implements ImageCycleViewListener{
@Override
public void onImageClick(View imageView) {
ElunboImg tag = (ElunboImg) imageView.getTag();
Bundle bundle = new Bundle();
bundle.putString(IntentConstant.AFTERGO, tag.getAftergo());
bundle.putString(IntentConstant.URL, tag.getUrl());
// if("news".equals(tag.getAftergo())){
// ActGuide.goBundle(getContext(),bundle, ActGuide.FRAG_ZXXQ);
// }
if("web".equals(tag.getAftergo())){
ActGuide.goBundle(getContext(),bundle, ActGuide.FRAG_LBWEB);
}
else {
ActGuide.go(getContext(), ActGuide.FRAG_DATACENTERS);
}
}
}
public ImageView getImageView(Context context, ElunboImg elunboImg) {
ImageView imageView = new ImageView(context);
imageView.setTag(elunboImg);
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
imageView.setScaleType(ScaleType.CENTER_CROP);
// imageView.setBackgroundResource(R.drawable.default_small);
return imageView;
}
}