Android 完美無限自動輪播 Banner

public class SlideShowViewSulz extends FrameLayout {
    private Context context;
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private boolean isPlay = true;
    private List<String> imageUrls;
    private List<View> dotViewsList;
    private LinearLayout dotLayout;
    private ViewPager viewPager;
    private int prePosition = 0;
    private int timeSpan;
    private static int defaultTimeSpan=5;
    private OnItemClickListener onItemClickListener;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (!isPlay || viewPager == null || viewPager.getChildCount() < 2)
                        return;
                    viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
                    break;
                default:
                    break;
            }
        }
    };

    private Thread mAutoPlayThread = new Thread() {
        @Override
        public void run() {
            while (true) {
                SystemClock.sleep(timeSpan * 1000);
                mHandler.sendEmptyMessage(1);
            }
        }
    };
    public SlideShowViewSulz(Context context) {
        this(context, defaultTimeSpan);
    }

    public SlideShowViewSulz(Context context, int timeSpan) {
        this(context, null, timeSpan);
    }

    public SlideShowViewSulz(Context context, AttributeSet attrs, int timeSpan) {
        this(context, attrs, 0, timeSpan);
    }

    public SlideShowViewSulz(Context context, AttributeSet attrs, int defStyle, int timeSpan) {
        super(context, attrs, defStyle);
        this.context = context;
        initImageLoader(context);
        mAutoPlayThread.start();
        this.timeSpan = timeSpan;
        initView();
    }

    private void initView() {
        LayoutInflater.from(context).inflate(R.layout.layout_slideshow, this, true);
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        ViewGroup.LayoutParams vParams = viewPager.getLayoutParams();
        vParams.height = (int) (DeviceHelper.getMobileWidth(context) * 0.52);
        viewPager.setLayoutParams(vParams);
        viewPager.setOnTouchListener(mOnTouchListener);
        ImageView ivSearch = (ImageView) findViewById(R.id.iv_search);
        ivSearch.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setClass(context, SearchActivity.class);
            context.startActivity(intent);
        });
    }


    public void setContent(List<String> imgDatalist) {
        if (imgDatalist == null || imgDatalist.size() == 0) {
            return;
        }
        imageUrls = imgDatalist;
        initUI();
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public void setTimeSpan(int timeSpan) {
        this.timeSpan = timeSpan;
    }

    /**
     * 初始化Views等UI
     */
    private void initUI() {
        initDotView();
        viewPager.setAdapter(new MyPagerAdapter());
        viewPager.setOnPageChangeListener(new MyPageChangeListener());
        viewPager.setCurrentItem(imageUrls.size() * 60);
    }

    private void initDotView() {
        if (dotLayout == null) {
            dotLayout = (LinearLayout) findViewById(R.id.dotLayout);
        } else {
            dotLayout.removeAllViews();
        }
        dotViewsList = new ArrayList<>();
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.leftMargin = 4;
        params.rightMargin = 4;
        for (int i = 0; i < imageUrls.size(); i++) {
            ImageView dotView = new ImageView(context);
            dotView.setBackgroundResource(R.mipmap.h2);
            dotLayout.addView(dotView, params);
            dotViewsList.add(dotView);
        }
        dotLayout.getChildAt(0).setBackgroundResource(R.mipmap.h1);
        dotViewsList.get(0).setBackgroundResource(R.mipmap.h1);
    }

    private class MyPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int pos) {
            dotViewsList.get(prePosition).setBackgroundResource(R.mipmap.h2);
            for (View v : dotViewsList) {
                v.setBackgroundResource(R.mipmap.h2);
            }
            dotViewsList.get(pos % dotViewsList.size()).setBackgroundResource(R.mipmap.h1);
            prePosition = pos % dotViewsList.size();
        }
    }

    OnTouchListener mOnTouchListener = new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    isPlay = false;
                    break;
                case MotionEvent.ACTION_MOVE:
                    isPlay = false;
                    break;
                case MotionEvent.ACTION_UP:
                    isPlay = true;
                    break;
                default:
                    break;
            }
            return false;
        }
    };

    /**
     * 填充ViewPager的頁面適配器
     */
    private class MyPagerAdapter extends PagerAdapter {

        //爲了複用
        private List<ImageView> imgCache = new ArrayList<ImageView>();

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            if (object != null && object instanceof ImageView) {
                ImageView iv = (ImageView) object;
                ((ViewPager) container).removeView(iv);
                imgCache.add(iv);
            }
        }

        @Override
        public Object instantiateItem(View container, final int position) {
            ImageView iv;
            //獲取ImageView對象
            if (imgCache.size() > 0) {
                iv = imgCache.remove(0);
            } else {
                iv = new ImageView(context);
            }
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            iv.setImageResource(R.mipmap.banner_null);
            imageLoader.displayImage(imageUrls.get(position % imageUrls.size()) + "", iv, new SimpleImageLoadingListener());
            iv.setOnClickListener(v -> onItemClickListener.onItemClick(iv, position % imageUrls.size()));
            ((ViewPager) container).addView(iv);
            return iv;
        }


        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {
        }

        @Override
        public void finishUpdate(View arg0) {
        }
    }

    private void initImageLoader(Context context) {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory().discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO)// Remove
                .build();
        ImageLoader.getInstance().init(config);
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }
}

先上代碼,可是請想要copy就用的各位同志注意一下,代碼中用到了第三方庫ImageLoader。無限輪播的實現其實就是講adapter的count設置了一個int類型的最大值,而後起始位置設爲輪播圖片數量的60倍,這樣,就實現了一開始就能夠左右滑動;固然,若是有人拼命讓圖片一直往左,終能滑到第一張繼而出現劃不動的狀況。因此這個數值能夠設大一點,可是不能設太大,由於筆者就由於設了int最大值的1/2而出現了程序ANR的狀況。請各位儘可能看懂代碼後操做,此篇爲思路文。若有問題歡迎留言一塊兒討論。ide

相關文章
相關標籤/搜索