轮播图

1、自定义滑动页面

public class AutoViewPager extends ViewPager {

    private static final int AUTO_WANT = 0x11;

    //数据源
    private List mList = new ArrayList<>();
    //轮播开关
    private boolean isStartAuto = false;
    //轮播间隔时长
    private int autoTime = 3000;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AUTO_WANT:
                    if (isStartAuto) {
                        int index = getCurrentItem();
                        //如果当前item超过了最大的页数
                        if (index >= mList.size() - 1) {
                            setCurrentItem(0);
                        } else {
                            setCurrentItem(index + 1);
                        }
                        mHandler.sendEmptyMessageDelayed(AUTO_WANT, autoTime);
                    }
                    break;
            }
        }
    };

    public AutoViewPager(Context context) {
        super(context);
    }

    public AutoViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    //设置轮播间隔时间
    public void setAutoTime(int autoTime) {
        this.autoTime = autoTime;
    }

    //获取轮播间隔时间
    public int getAutoTime() {
        return autoTime;
    }

    //启动轮播
    public void setStartAuto(boolean startAuto) {
        isStartAuto = startAuto;
        if (startAuto) {
            mHandler.sendEmptyMessage(AUTO_WANT);
        } else {
            mHandler.removeMessages(AUTO_WANT);
        }
    }

    public boolean getStartAuto() {
        return isStartAuto;
    }

    //获取当前轮播状态
    public boolean isStartAuto() {
        return isStartAuto;
    }

    //设置view
    public void setView(View view) {
        mList.add(view);
        setAdapter(new BasePagerAdapter(mList));

        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //接口传参  position
            }
        });
    }
}

2、在布局中引用

  <com.***.view.AutoViewPager
            android:id="@+id/mAutoViewPager"
            android:layout_width="match_parent"
            android:layout_height="200dp"/>

3、使用

mAutoViewPager = (AutoViewPager) findViewById(R.id.mAutoViewPager);
        mAutoViewPager.setAutoTime(2000);
        mAutoViewPager.setStartAuto(true);

 for (int i = 0; i < model.getData().getPhoto().size(); i++) {
            View view = View.inflate(this, R.layout.layout_auto_view_pager_item, null);
            ImageView iv = (ImageView) view.findViewById(R.id.iv_bg);
            GlideUtils.loadImageviewCenterCrop(this, model.getData().getPhoto().get(i), iv);
            mAutoViewPager.setView(view);
        }

你可能感兴趣的:(Util类,Android知识)