一款好用的廣告無限輪播工具類
阿新 • • 發佈:2018-12-11
1.先上效果圖
2.自定義工具類AdViewpagerUtil.java
import android.content.Context; import android.os.Handler; import android.support.v4.view.ViewPager; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import com.bumptech.glide.Glide; /** * 首頁廣告圖片相關工具類 */ public class AdViewpagerUtil { private Context context; private ViewPager viewPager; private ImageViewPagerAdapter mimageViewPagerAdapter; private ImageView[] mImageViews; private Integer[] urls; private LinearLayout dotlayout; private ImageView[] dotViews; private boolean isRight = true; // 判斷viewpager是不是向右滑動 private int lastPosition = 1; // 記錄viewpager從哪個頁面滑動到當前頁面,從而區分滑動方向 private int autoIndex = 1; // 自動輪詢時自增座標,能確定導航圓點的位置 private int currentIndex = 0; //當前item private int delayTime = 5000; //自動輪播的時間間隔 private int imgsize = 0; //圖片的數量,item的數量 private boolean isLoop = false; //輪播開關 private OnAdPageChangeListener onAdPageChangeListener; //pagechange回撥 private OnAdItemClickListener onAdItemClickListener; //點選事件回撥 private int dotsize = 8; //小圓點的大小寬度 private int dotoffset = 4; //小圓點的間距 /** * 不帶小圓點 * * @param context * @param viewPager * @param urls */ public AdViewpagerUtil(Context context, ViewPager viewPager, Integer[] urls) { this.context = context; this.viewPager = viewPager; this.urls = urls; } /** * 有小圓點 * * @param context * @param viewPager * @param dotlayout * @param dotsize * @param dotoffset * @param urls */ public AdViewpagerUtil(Context context, ViewPager viewPager, LinearLayout dotlayout, int dotsize, int dotoffset, Integer[] urls) { this.context = context; this.viewPager = viewPager; this.dotlayout = dotlayout; this.dotsize = dotsize; this.urls = urls; } public void setOnAdPageChangeListener(OnAdPageChangeListener onAdPageChangeListener) { this.onAdPageChangeListener = onAdPageChangeListener; } public void setOnAdItemClickListener(OnAdItemClickListener onAdItemClickListener) { this.onAdItemClickListener = onAdItemClickListener; } private void initAdimgs(Integer[] urls) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); int length = urls.length + 2; mImageViews = new ImageView[length]; for (int i = 0; i < length; i++) { ImageView imageView = new ImageView(context); imageView.setLayoutParams(params); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); mImageViews[i] = imageView; } setImg(length, urls); } private void setImg(int length, Integer[] urls) { if (urls.length > 0) { imgsize = length; for (int i = 0; i < length; i++) { if (i < length - 2) { final int index = i; Glide.with(context).load(urls[i]).into(mImageViews[i + 1]); mImageViews[i + 1].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (onAdItemClickListener != null) { onAdItemClickListener.onItemClick(mImageViews[index + 1], index); } } }); } } Glide.with(context).load(urls[urls.length - 1]).into(mImageViews[0]); Glide.with(context).load(urls[0]).into(mImageViews[length - 1]); } } public void initVps() { initAdimgs(urls); initDots(urls.length); mimageViewPagerAdapter = new ImageViewPagerAdapter(context, mImageViews); viewPager.setAdapter(mimageViewPagerAdapter); viewPager.setOffscreenPageLimit(mImageViews.length); startLoopViewPager(); viewPager.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: isLoop = true; stopLoopViewPager(); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: isLoop = false; startLoopViewPager(); default: break; } return false; } }); viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrollStateChanged(int arg0) { if (isRight) { if (arg0 != 1) { if (lastPosition == 0) { viewPager.setCurrentItem(imgsize - 2, false); } else if (lastPosition == imgsize - 1) { viewPager.setCurrentItem(1, false); } } } if (onAdPageChangeListener != null) { onAdPageChangeListener.onPageScrollStateChanged(arg0); } } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { // TODO Auto-generated method stub if (!isRight) { if (arg1 < 0.01) { if (arg0 == 0) { viewPager.setCurrentItem(imgsize - 2, false); } else if (arg0 == imgsize - 1) { viewPager.setCurrentItem(1, false); } } } if (onAdPageChangeListener != null) { onAdPageChangeListener.onPageScrolled(arg0, arg1, arg2); } } @Override public void onPageSelected(int arg0) { // TODO Auto-generated method stub autoIndex = arg0; if (lastPosition < arg0 && lastPosition != 0) { isRight = true; } else if (lastPosition == imgsize - 1) { isRight = true; } if (lastPosition > arg0 && lastPosition != imgsize - 1) { isRight = false; } else if (lastPosition == 0) { isRight = false; } lastPosition = arg0; if (arg0 == 0) { currentIndex = imgsize - 2; } else if (arg0 == imgsize - 1) { currentIndex = 1; } else { currentIndex = arg0; } for (int i = 0; i < dotViews.length; i++) { if (i == currentIndex - 1) { dotViews[i].setSelected(true); } else { dotViews[i].setSelected(false); } } if (onAdPageChangeListener != null) { onAdPageChangeListener.onPageSelected(arg0); } } }); viewPager.setCurrentItem(1);// 初始化時設定顯示第一頁(ViewPager中索引為1) } public void initDots(int length) { if (dotlayout == null) return; dotlayout.removeAllViews(); LinearLayout.LayoutParams mParams = new LinearLayout.LayoutParams(dip2px(context, dotsize), dip2px(context, dotsize)); mParams.setMargins(dip2px(context, dotoffset), 0, dip2px(context, dotoffset), 0);//設定小圓點左右之間的間隔 dotViews = new ImageView[length]; for (int i = 0; i < length; i++) { ImageView imageView = new ImageView(context); imageView.setLayoutParams(mParams); imageView.setImageResource(R.drawable.dot_selector); if (i == 0) { imageView.setSelected(true);//預設啟動時,選中第一個小圓點 } else { imageView.setSelected(false); } dotViews[i] = imageView;//得到每個小圓點的引用,用於滑動頁面時,(onPageSelected方法中)更改它們的狀態。 dotlayout.addView(imageView);//新增到佈局裡面顯示 } } Handler handler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { // 要做的事情 if (viewPager.getChildCount() > 0) { handler.postDelayed(this, delayTime); autoIndex++; viewPager.setCurrentItem(autoIndex % imgsize, true); } } }; private void startLoopViewPager() { if (!isLoop && viewPager != null) { handler.postDelayed(runnable, delayTime);// 每兩秒執行一次runnable. isLoop = true; } } private void stopLoopViewPager() { if (isLoop && viewPager != null) { handler.removeCallbacks(runnable); isLoop = false; } } public interface OnAdItemClickListener { void onItemClick(View v, int flag); } public interface OnAdPageChangeListener { void onPageScrollStateChanged(int arg0); void onPageScrolled(int arg0, float arg1, int arg2); void onPageSelected(int arg0); } public int dip2px(Context context, float dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dipValue * scale + 0.5f); } }
3. xml檔案
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="210dp"> <android.support.v4.view.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fff" /> <LinearLayout android:id="@+id/llDots" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="12dp" android:orientation="horizontal" /> </RelativeLayout>
注意:ViewPager的包型別要和AdViewpagerUtil.java中的ViewPager包名保持一致,目前我用的是v4包裡的ViewPager。
4.呼叫工具類
(1)靜態資料填充
viewPager = (ViewPager) findViewById(R.id.viewPager); llDots = (LinearLayout) findViewById(R.id.llDots); //靜態資料填充 imgs = new Integer[]{R.drawable.pic01, R.drawable.pic02, R.drawable.pic03}; adViewpagerUtil = new AdViewpagerUtil(this, viewPager, llDots, 8, 2, imgs); adViewpagerUtil.initVps();
(2)虛擬動態資料填充
List<String> imgList = new ArrayList<>();
if (proModel.getImages() != null) {
if (proModel.getImages().size() > 0) {
for (int i = 0; i < proModel.getImages().size(); i++) {
imgList.add(ApiManage.HOST_URL + proModel.getImages().get(i));
}
}
}
adViewpagerUtil = new AdViewpagerUtil(this, viewPager, llDots, 8, 2, imgList);
adViewpagerUtil.initViewPager();
(3)監聽廣告翻頁狀態
adViewpagerUtil.setOnAdPageChangeListener(new AdViewpagerUtil.OnAdPageChangeListener() {
@Override
public void onPageScrollStateChanged(int arg0) {
Toast.makeText(MainActivity.this, "第" + arg0 + "頁", Toast.LENGTH_LONG).show();
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int arg0) {
}
});
(4)監聽廣告頁 點選狀態
adViewpagerUtil.setOnAdItemClickListener(new AdViewpagerUtil.OnAdItemClickListener() {
@Override
public void onItemClick(View v, int flag) {
Toast.makeText(MainActivity.this, "第" + flag + "頁", Toast.LENGTH_LONG).show();
}
});
5.附上原始碼 歡迎留言討論