美文网首页
ViewPager轮播实现

ViewPager轮播实现

作者: JokAr_ | 来源:发表于2017-08-27 22:49 被阅读566次

最近想要实现一个自定义一个viewPager实现广播轮播的效果,但是网上找了许多很多杰作,有的并不是太好比如改写view count的值为Int的最大值什么的,有的就是嵌套其他东西太多,我只想要个轮播的viewPager而他的包里包含了太多其他东西/(ㄒoㄒ)/~~;
所以还是还是手撸一个吧;实现的思路就是改写viewPager用postDelayed来实现轮播,并且还要解决手指拖拽viewPager时自动轮播要停止的问题;so,上代码吧:

1.定义Runnable

kotlin

private val autoScrollRunnable = object : Runnable {
        override fun run() {
            if (currentItem == adapter.count - 1) {
//                currentItem = 0
                setCurrentItem(0, false)
            } else {
                currentItem += 1
            }
            postDelayed(this, duration.toLong())
        }
    }

Java

private Runnable autoScrollRunnable = new Runnable() {
        @Override
        public void run() {
            if (getCurrentItem() == getAdapter().getCount() - 1) {
//                currentItem = 0
                setCurrentItem(0, false);
            } else {
                setCurrentItem(getCurrentItem() + 1);
            }
            postDelayed(autoScrollRunnable, duration);
        }
    };

2.定义styleable方便自定义使用

 <declare-styleable name="AutoScrollViewPager">
        <attr format="boolean" name="indeterminate"/>
        <attr format="boolean" name="autoScroll"/>
        <attr format="integer" name="duration"/>
    </declare-styleable>

kotlin

  private val default_duration = 2000
    var duration = default_duration
    //是否自动滚动
    private var autoScroll = true
    //是否循环滚动
    private var indeterminate = true

    private var startX = 0f

    constructor(context: Context) : this(context, null)

    init {
        var typeArray = context.obtainStyledAttributes(attrs, R.styleable.AutoScrollViewPager)

        duration = typeArray.getInt(R.styleable.AutoScrollViewPager_duration, default_duration)
        setAutoScrollEnabled(typeArray.getBoolean(R.styleable.AutoScrollViewPager_autoScroll, true))
        indeterminate = typeArray.getBoolean(R.styleable.AutoScrollViewPager_indeterminate, true)

        typeArray.recycle()

    }

Java

 private final int default_duration = 2000;

    private int duration = default_duration;
    /**
     * 是否自动滚动
     */
    private boolean autoScroll = true;
    /**
     * 是否循环滚动
     */
    private boolean indeterminate = true;

    private float startX = 0;

    public AutoScrollViewPager2(Context context) {
        this(context, null);
    }

    public AutoScrollViewPager2(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AutoScrollViewPager);
        duration = typedArray.getInt(R.styleable.AutoScrollViewPager_duration, default_duration);
        setAutoScrollEnabled(typedArray.getBoolean(R.styleable.AutoScrollViewPager_autoScroll, true));
        indeterminate = typedArray.getBoolean(R.styleable.AutoScrollViewPager_indeterminate, true);

        typedArray.recycle();
    }

3.定义一些方法

kotlin

internal fun setAutoScrollEnabled(value: Boolean) {
        autoScroll = value

        if (autoScroll) {
            startAutoScroll()
        }
    }
 private fun startAutoScroll() {
        stopAutoScroll()
        postDelayed(autoScrollRunnable, duration.toLong())
    }
    private fun stopAutoScroll() {
        removeCallbacks(autoScrollRunnable)
    }

Java

 public void setAutoScrollEnabled(boolean value) {
        autoScroll = value;

        if (autoScroll) {
            startAutoScroll();
        }
    }
 private void startAutoScroll() {
        stopAutoScroll();
        postDelayed(autoScrollRunnable, duration);
    }

    private void stopAutoScroll() {
        removeCallbacks(autoScrollRunnable);
    }

4. 自动调用轮播

kotlin

 override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        setAutoScrollEnabled(autoScroll)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopAutoScroll()
    }

    override fun onWindowFocusChanged(hasWindowFocus: Boolean) {
        super.onWindowFocusChanged(hasWindowFocus)
        if (hasWindowFocus) {
            setAutoScrollEnabled(autoScroll)
        } else {
            stopAutoScroll()
        }
    }

Java

 @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        setAutoScrollEnabled(autoScroll);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopAutoScroll();
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        if (hasWindowFocus) {
            setAutoScrollEnabled(autoScroll);
        } else {
            stopAutoScroll();
        }
    }

这里会涉及到一个问题,就是View的post(Runnable)方法非100%执行,原因和处理方法在这里

5.手指拖拽viewPager时停止自动轮播

kotlin

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        try {
            when(event.actionMasked){
                MotionEvent.ACTION_DOWN ->{
                    //按下手指停止自动滚动
                    stopAutoScroll()
                    startX = event.x
                }
            }
            return super.onInterceptTouchEvent(event)
        } catch (e: Exception) {
            JLog.e(e)
        }
        return true
    }
    override fun onTouchEvent(ev: MotionEvent): Boolean {
        try {
            when (ev.action and MotionEvent.ACTION_MASK) {
                MotionEvent.ACTION_UP -> {
                    //如果indeterminate为true则手指滑动到最后一个时再滑动则跳到一个view
                    if (indeterminate
                            && (currentItem == 0 || currentItem == adapter.count - 1)) {

                        if (currentItem == adapter.count - 1
                                && (ev.x < startX && startX - ev.x > 50)) {
                            postDelayed({ setCurrentItem(0, false) },
                                    100)
                        }
                    }
                    //移开手指开始自动滚动
                    startAutoScroll()
                }
            }
            return super.onTouchEvent(ev)
        } catch (e: Exception) {
            JLog.e(e)
        }
        return false
    }

Java

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        try {
            switch (ev.getActionMasked()) {
                case MotionEvent.ACTION_DOWN: {
                    //按下手指停止自动滚动
                    stopAutoScroll();
                    startX = ev.getX();
                    break;
                }
            }
            return super.onInterceptTouchEvent(ev);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        try {
            switch (ev.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_UP: {
                    //如果indeterminate为true则手指滑动到最后一个时再滑动则跳到一个view
                    if (indeterminate
                            && (getCurrentItem() == 0
                            || getCurrentItem() == getAdapter().getCount() - 1)) {

                        if (getCurrentItem() == getAdapter().getCount() - 1
                                && (ev.getX() < startX && startX - ev.getX() > 50)) {
                            postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    setCurrentItem(0, false);
                                }
                            }, 200);
                        }
                    }
                    //移开手指开始自动滚动
                    startAutoScroll();
                    break;
                }
            }
            return super.onTouchEvent(ev);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

这就ok了,最后奉上完整代码,(Kotlin):

/**
 * Created by JokAr on 2017/6/22.
 */
open class AutoScrollViewPager @JvmOverloads constructor(context: Context, attrs: AttributeSet?)
    : ViewPager(context, attrs) {



    private val default_duration = 2000
    var duration = default_duration
    //是否自动滚动
    private var autoScroll = true
    //是否循环滚动
    private var indeterminate = true

    private var startX = 0f

    constructor(context: Context) : this(context, null)

    init {
        var typeArray = context.obtainStyledAttributes(attrs, R.styleable.AutoScrollViewPager)

        duration = typeArray.getInt(R.styleable.AutoScrollViewPager_duration, default_duration)
        setAutoScrollEnabled(typeArray.getBoolean(R.styleable.AutoScrollViewPager_autoScroll, true))
        indeterminate = typeArray.getBoolean(R.styleable.AutoScrollViewPager_indeterminate, true)

        typeArray.recycle()
    }

    private val autoScrollRunnable = object : Runnable {
        override fun run() {
            if (currentItem == adapter.count - 1) {
//                currentItem = 0
                setCurrentItem(0, false)
            } else {
                currentItem += 1
            }
            postDelayed(this, duration.toLong())
        }
    }

    internal fun setAutoScrollEnabled(value: Boolean) {
        autoScroll = value

        if (autoScroll) {
            startAutoScroll()
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        setAutoScrollEnabled(autoScroll)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopAutoScroll()
    }

    override fun onWindowFocusChanged(hasWindowFocus: Boolean) {
        super.onWindowFocusChanged(hasWindowFocus)
        if (hasWindowFocus) {
            setAutoScrollEnabled(autoScroll)
        } else {
            stopAutoScroll()
        }
    }

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        try {
            when(event.actionMasked){
                MotionEvent.ACTION_DOWN ->{
                    //按下手指停止自动滚动
                    stopAutoScroll()
                    startX = event.x
                }
            }
            return super.onInterceptTouchEvent(event)
        } catch (e: Exception) {
            JLog.e(e)
        }
        return true
    }

    override fun onTouchEvent(ev: MotionEvent): Boolean {
        try {
            when (ev.action and MotionEvent.ACTION_MASK) {
                MotionEvent.ACTION_UP -> {
                    //如果indeterminate为true则手指滑动到最后一个时再滑动则跳到一个view
                    if (indeterminate
                            && (currentItem == 0 || currentItem == adapter.count - 1)) {

                        if (currentItem == adapter.count - 1
                                && (ev.x < startX && startX - ev.x > 50)) {
                            postDelayed({ setCurrentItem(0, false) },
                                    100)
                        }
                    }
                    //移开手指开始自动滚动
                    startAutoScroll()
                }
            }
            return super.onTouchEvent(ev)
        } catch (e: Exception) {
            JLog.e(e)
        }
        return false
    }


    private fun startAutoScroll() {
        stopAutoScroll()
        postDelayed(autoScrollRunnable, duration.toLong())
    }

    private fun stopAutoScroll() {
        removeCallbacks(autoScrollRunnable)
    }
}

Java版:

/**
 * Created by JokAr on 2017/8/28.
 */

public class AutoScrollViewPager extends ViewPager {
    private final int default_duration = 2000;

    private int duration = default_duration;
    /**
     * 是否自动滚动
     */
    private boolean autoScroll = true;
    /**
     * 是否循环滚动
     */
    private boolean indeterminate = true;

    private float startX = 0;

    public AutoScrollViewPager2(Context context) {
        this(context, null);
    }

    public AutoScrollViewPager2(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AutoScrollViewPager);
        duration = typedArray.getInt(R.styleable.AutoScrollViewPager_duration, default_duration);
        setAutoScrollEnabled(typedArray.getBoolean(R.styleable.AutoScrollViewPager_autoScroll, true));
        indeterminate = typedArray.getBoolean(R.styleable.AutoScrollViewPager_indeterminate, true);

        typedArray.recycle();
    }

    private Runnable autoScrollRunnable = new Runnable() {
        @Override
        public void run() {
            if (getCurrentItem() == getAdapter().getCount() - 1) {
//                currentItem = 0
                setCurrentItem(0, false);
            } else {
                setCurrentItem(getCurrentItem() + 1);
            }
            postDelayed(autoScrollRunnable, duration);
        }
    };

    public void setAutoScrollEnabled(boolean value) {
        autoScroll = value;

        if (autoScroll) {
            startAutoScroll();
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        setAutoScrollEnabled(autoScroll);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopAutoScroll();
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        if (hasWindowFocus) {
            setAutoScrollEnabled(autoScroll);
        } else {
            stopAutoScroll();
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        try {
            switch (ev.getActionMasked()) {
                case MotionEvent.ACTION_DOWN: {
                    //按下手指停止自动滚动
                    stopAutoScroll();
                    startX = ev.getX();
                    break;
                }
            }
            return super.onInterceptTouchEvent(ev);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        try {
            switch (ev.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_UP: {
                    //如果indeterminate为true则手指滑动到最后一个时再滑动则跳到一个view
                    if (indeterminate
                            && (getCurrentItem() == 0
                            || getCurrentItem() == getAdapter().getCount() - 1)) {

                        if (getCurrentItem() == getAdapter().getCount() - 1
                                && (ev.getX() < startX && startX - ev.getX() > 50)) {
                            postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    setCurrentItem(0, false);
                                }
                            }, 200);
                        }
                    }
                    //移开手指开始自动滚动
                    startAutoScroll();
                    break;
                }
            }
            return super.onTouchEvent(ev);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    private void startAutoScroll() {
        stopAutoScroll();
        postDelayed(autoScrollRunnable, duration);
    }

    private void stopAutoScroll() {
        removeCallbacks(autoScrollRunnable);
    }
}

相关文章

  • Banner

    利用** ViewPager **实现广告 Banner 循环轮播。

  • Android无限轮播Banner的实现

    概述 应用首页的广告轮播Banner,一般都会使用ViewPager来实现,但是ViewPager 没有轮播效果。...

  • android轮播图效果

    先上效果图: viewpager+handler+runnableTask实现轮播图效果。可以自动轮播,左右无限滑...

  • Android ViewPager 无限轮播Integer.MA

    Android ViewPager没有实现无限轮播功能。 开发者为了实现无限轮播,一种比较流行但又备受争议、猜疑的...

  • ViewPager轮播实现

    最近想要实现一个自定义一个viewPager实现广播轮播的效果,但是网上找了许多很多杰作,有的并不是太好比如改写v...

  • ViewPager2

    一. ViewPager2实现无限轮播 废话不多说直接上代码

  • ViewPager实现图片轮播

    自己实现的ViewPager轮播,做的比较蠢,使用setCurrentItem(i,false)去掉动画得以实现....

  • 广告轮播图

    轮播图使用ViewPager来实现,我没有抽取为view,直接在activity中实现 public class ...

  • Android ViewPager2实现无限轮播

    Android轮播控件 全新升级,基于ViewPager2实现无限轮播功能。可以自定义indicator,需自定义...

  • 【Android寻坑之路】ViewPager实现无限轮播切换页面

    问题产生背景 在使用ViewPager实现无限轮播效果时,为了达到无缝对接的效果,我在ViewPager的最左侧(...

网友评论

      本文标题:ViewPager轮播实现

      本文链接:https://www.haomeiwen.com/subject/dhzelxtx.html