package com.qianbao.financeforyou.widgit; import android.content.Context; import android.os.Handler; import android.os.Message; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateInterpolator; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.qianbao.financeforyou.R; import com.qianbao.financeforyou.model.AppConfig; import com.qianbao.financeforyou.views.fragment.ShouYeFragment; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2018/8/15. */ public class SlideShowViewPager extends FrameLayout implements ViewPager.OnPageChangeListener{ private static final String TAG = "CycleViewPager"; private Context mContext; private static float MIN_SCALE = 0.85f; private static float MIN_ALPHA = 0.5f; private ViewPager mViewPager;//实现轮播图的ViewPager private Handler handler;//每几秒后执行下一张的切换 private int WHEEL = 100; // 转动 private int WHEEL_WAIT = 101; // 等待 private List<View> mViews = new ArrayList<>(); //需要轮播的View,数量为轮播图数量+2 private List<AppConfig.BannerAdsBean> AdProducts;//数据集合 private boolean isScrolling = false; // 滚动框是否滚动着 private boolean isCycle = true; // 是否循环,默认为true private boolean isWheel = true; // 是否轮播,默认为true private int delay = 4000; // 默认轮播时间 private int mCurrentPosition = 0; // 轮播当前位置 private long releaseTime = 0; // 手指松开、页面不滚动时间,防止手机松开后短时间进行切换 private ViewPagerAdapter mAdapter; private ImageCycleViewListener mImageCycleViewListener; final Runnable runnable = new Runnable() { @Override public void run() { if (mContext != null && isWheel) { long now = System.currentTimeMillis(); // 检测上一次滑动时间与本次之间是否有触击(手滑动)操作,有的话等待下次轮播 if (now - releaseTime > delay - 500) { handler.sendEmptyMessage(WHEEL); } else { handler.sendEmptyMessage(WHEEL_WAIT); } } } }; public SlideShowViewPager(Context context) { this(context, null); } public SlideShowViewPager(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SlideShowViewPager(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.mContext = context; initView(); } /** * 初始化View */ private void initView() { View view = LayoutInflater.from(mContext).inflate(R.layout.one, this,true); mViewPager = (ViewPager) view.findViewById(R.id.cycle_view_pager); try { Field mField = ViewPager.class.getDeclaredField("mScroller"); mField.setAccessible(true); SpeedScroller speedScroller = new SpeedScroller(mViewPager.getContext(),new AccelerateInterpolator()); mField.set(mViewPager,speedScroller); }catch (Exception e){ e.printStackTrace(); } handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == WHEEL && mViews.size() > 0) { if (!isScrolling) { //当前为非滚动状态,切换到下一页 int posttion = (mCurrentPosition + 1) % mViews.size(); mViewPager.setCurrentItem(posttion, true); } releaseTime = System.currentTimeMillis(); handler.removeCallbacks(runnable); handler.postDelayed(runnable, delay); return; } if (msg.what == WHEEL_WAIT && mViews.size() > 0) { handler.removeCallbacks(runnable); handler.postDelayed(runnable, delay); } } }; } public void setData(List<AppConfig.BannerAdsBean> list, ImageCycleViewListener listener) { setData(list, listener, 0); } /** * 初始化viewpager * * @param list 要显示的数据 * @param showPosition 默认显示位置 */ public void setData(List<AppConfig.BannerAdsBean> list, ImageCycleViewListener listener, int showPosition) { Log.i("wanlijun","list.size()="+list.size()); if (list == null || list.size() == 0) { //没有数据时隐藏整个布局 this.setVisibility(View.GONE); return; } mViews.clear(); AdProducts = list; Log.i("wanlijun","stringList.size()="+AdProducts.size()); Log.i("wanlijun","isCycle="+isCycle); if (isCycle) { //添加轮播图View,数量为集合数+2 // 将最后一个View添加进来 mViews.add(getImageView(mContext, AdProducts.get(AdProducts.size() - 1).thumb)); for (int i = 0; i < AdProducts.size(); i++) { mViews.add(getImageView(mContext, AdProducts.get(i).thumb)); } // 将第一个View添加进来 mViews.add(getImageView(mContext, AdProducts.get(0).thumb)); } else { //只添加对应数量的View for (int i = 0; i < AdProducts.size(); i++) { mViews.add(getImageView(mContext, AdProducts.get(i).thumb)); } } if (mViews == null || mViews.size() == 0) { //没有View时隐藏整个布局 this.setVisibility(View.GONE); return; } mImageCycleViewListener = listener; mAdapter = new ViewPagerAdapter(); mViewPager.setPageMargin(10); mViewPager.setOffscreenPageLimit(3); mViewPager.setPageTransformer(true, new ViewPager.PageTransformer() { @Override public void transformPage(View view, float position) { int pageWidth = view.getWidth(); int pageHeight = view.getHeight(); float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position)); float vertMargin = pageHeight * (1 - scaleFactor) / 2; float horzMargin = pageWidth * (1 - scaleFactor) / 2; if (position < 0) { view.setTranslationX(horzMargin - vertMargin / 2); } else { view.setTranslationX(-horzMargin + vertMargin / 2); } // Scale the page down (between MIN_SCALE and 1) view.setScaleX(scaleFactor); view.setScaleY(scaleFactor); // Fade the page relative to its size. // view.setAlpha(MIN_ALPHA + (scaleFactor - MIN_SCALE) // / (1 - MIN_SCALE) * (1 - MIN_ALPHA)); } }); mViewPager.setOnPageChangeListener(this); mViewPager.setAdapter(mAdapter); if (showPosition < 0 || showPosition >= mViews.size()) showPosition = 0; if (isCycle) { showPosition = showPosition + 1; } mViewPager.setCurrentItem(showPosition); setWheel(true);//设置轮播 } /** * 获取轮播图View * * @param context * @param url */ private View getImageView(Context context, String url) { return ShouYeFragment.getImageView(context, url); } // public static View getImageView(Context context, int id) { // RelativeLayout rl = new RelativeLayout(context); // RoundRectangleImageView imageView = new RoundRectangleImageView(context); // RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); // imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); // imageView.setLayoutParams(layoutParams); // imageView.setImageResource(id); // rl.addView(imageView); // return rl; // } /** * 页面适配器 返回对应的view * * @author Yuedong Li */ private class ViewPagerAdapter extends PagerAdapter { @Override public int getCount() { return mViews.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) { Log.i("wanlijun","position="+position); View v = mViews.get(position); if (mImageCycleViewListener != null) { v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mImageCycleViewListener.onImageClick(AdProducts.get(mCurrentPosition-1), mCurrentPosition, v); } }); } container.addView(v); return v; } @Override public int getItemPosition(Object object) { return POSITION_NONE; } // @Override // public float getPageWidth(int position) { // return 0.8f; // } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int arg0) { int max = mViews.size() - 1; int position = arg0; mCurrentPosition = arg0; if (isCycle) { if (arg0 == 0) { //滚动到mView的1个(界面上的最后一个),将mCurrentPosition设置为max - 1 mCurrentPosition = max - 1; } else if (arg0 == max) { //滚动到mView的最后一个(界面上的第一个),将mCurrentPosition设置为1 mCurrentPosition = 1; } position = mCurrentPosition - 1; } } @Override public void onPageScrollStateChanged(int state) { if (state == 1) { // viewPager在滚动 isScrolling = true; return; } else if (state == 0) { // viewPager滚动结束 releaseTime = System.currentTimeMillis(); //跳转到第mCurrentPosition个页面(没有动画效果,实际效果页面上没变化) mViewPager.setCurrentItem(mCurrentPosition, false); } isScrolling = false; } /** * 为textview设置文字 * * @param textView * @param text */ public static void setText(TextView textView, String text) { if (text != null && textView != null) textView.setText(text); } /** * 为textview设置文字 * * @param textView * @param text */ public static void setText(TextView textView, int text) { if (textView != null) setText(textView, text + ""); } /** * 是否循环,默认开启。必须在setData前调用 * * @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, delay); } } /** * 刷新数据,当外部视图更新后,通知刷新数据 */ public void refreshData() { if (mAdapter != null) mAdapter.notifyDataSetChanged(); } /** * 是否处于轮播状态 * * @return */ public boolean isWheel() { return isWheel; } /** * 设置轮播暂停时间,单位毫秒(默认4000毫秒) * @param delay */ public void setDelay(int delay) { this.delay = delay; } /** * 轮播控件的监听事件 * * @author minking */ public static interface ImageCycleViewListener { /** * 单击图片事件 * * @param resourceId * @param position * @param imageView */ public void onImageClick(AppConfig.BannerAdsBean AdProduct, int position, View imageView); } }
圆角矩形:
public class RoundRectangleImageView extends ImageView { private Paint paint; public RoundRectangleImageView(Context context) { this(context,null); } public RoundRectangleImageView(Context context, AttributeSet attrs) { this(context, attrs,0); } public RoundRectangleImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); paint = new Paint(Paint.ANTI_ALIAS_FLAG); } @Override protected void onDraw(Canvas canvas) { Drawable drawable = getDrawable(); if (null != drawable) { Bitmap bitmap = drawable2Bitmap(drawable); Bitmap b = getRoundBitmap(bitmap, 30); final Rect rectSrc = new Rect(0, 0, b.getWidth(), b.getHeight()); final Rect rectDest = new Rect(0, 0, getWidth(), getHeight()); paint.reset(); canvas.drawBitmap(b, rectSrc, rectDest, paint); } else { super.onDraw(canvas); } } private Bitmap getRoundBitmap(Bitmap bitmap, int roundPx) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); int x = bitmap.getWidth(); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } private Bitmap drawable2Bitmap(Drawable drawable) { if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else{ // Bitmap bitmap = Bitmap // .createBitmap( // drawable.getIntrinsicWidth(), // drawable.getIntrinsicHeight(), // drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 // : Bitmap.Config.RGB_565); Bitmap bitmap = Bitmap .createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; } } }
轮播图动画速度:
public class SpeedScroller extends Scroller { public SpeedScroller(Context context) { super(context); } public SpeedScroller(Context context, Interpolator interpolator) { super(context, interpolator); } @Override public void startScroll(int startX, int startY, int dx, int dy) { super.startScroll(startX, startY, dx, dy,300); } @Override public void startScroll(int startX, int startY, int dx, int dy, int duration) { super.startScroll(startX, startY, dx, dy, 300); } }