LoopView-循环轮播控件

499 查看


这次我们来学习一下日常看到的广告轮播器,几乎每个App中都拥有这样的控件。这种使用频繁的控件,我们应该懂得它们的实现原理,这样我们在使用的工程中就能更加熟练与轻松。先来看下效果吧。

效果图

原理

其实这个控件的实现本质就是一个ViewPager,相信大家对ViewPager不会很陌生,例如ViewPager+Fragment实现新闻的界面。首先我们要明确我们所要的需求,我们要实现ViewPager滑动切换画面,同时最重要的是它自己能循环切换。好了,下面我来简要的解释下核心的实现。

初始化

要实现一个轮播控件,所以我们首先要自定义LoopView控件,设置相关布局文件,与初始化一些比较的事件,例如绑定控件、设置监听与获取自定义属性值。这里布局我就不多说了,可以自行查看。

public void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.loopview_layout, this, true);
        viewPager = (ViewPager) findViewById(R.id.loopView);
        linearCircler = (LinearLayout) findViewById(R.id.linear_circler);
        linearCirclerNo = (LinearLayout) findViewById(R.id.linear_circler_no);
        descript = (TextView) findViewById(R.id.descript);
        viewPager.addOnPageChangeListener(this);
        viewPager.setOnTouchListener(this);
    }

这是一些必要的布局填充与监听绑定,同时我这里自定义了属性,所以也要获取

public LoopView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.LoopView);
        rate = typedArray.getInteger(R.styleable.LoopView_rate, DEF_RATE);
        bottomStyle = typedArray.getInteger(R.styleable.LoopView_bottom_style, DEF_BOTTOM_STYLE);
        init(context);
    }

其中rate代表下面会提到的轮播的速度,bottomStyle代表的是LoopView的样式。这些属性都是在布局文件中设置。

addOnPageChangeListener

这个是监听LoopViewViewPager控件的pager切换。要实现它的三个方法onPageScrolledonPageSelectedonPageScrollStateChanged我们这里要用的是后面两个方法。

onPageSelected

在这个方法中我们要实现对界面中圆点选中切换与描述文本的内容的变更,代码不是很多,直接看源码。

 @Override
    public void onPageSelected(int position) {
        mCurrentPos = position;
        //是否有描述文本
        if (bottomStyle == getResources().getInteger(R.integer.loop_have_descript))
            descript.setText(list.get(position).getDescript());
        for (int i = 0; i < linearLayout.getChildCount(); i++) {      
            //圆点切换  
            if (i == position)
                linearLayout.getChildAt(i).setSelected(true);
            else
                linearLayout.getChildAt(i).setSelected(false);
        }
    }

onPageScrollStateChanged

好了,这里我们就可以实现对于手动滑动到最后一个向第一个切换或从第一个到最后一个切换。

@Override
    public void onPageScrollStateChanged(int state) {
        switch (state) {
            case SCROLL_COMPLETELY:
                //最后一个到第一个
                if (viewPager.getCurrentItem() == list.size() - 1 && !isChanged) {
                    viewPager.setCurrentItem(0);
                }
                //第一个到最后一个
                if (viewPager.getCurrentItem() == 0 && !isChanged) {
                    viewPager.setCurrentItem(list.size() - 1);
                }
                break;
            case SCROLL_NO_SELECT:
                isChanged = false;
                break;
            case SCROLL_SELECTED:
                isChanged = true;
                break;
        }
    }

setOnTouchListener

实现触摸监听主要是为了防止在我们手动切换时,LoopView还在自己循环切换,这样就使得我们手动切换时不协调。我们要做的就是手指触摸到LoopView时停止自动循环,即ACTION_DOWNACTION_MOVE。在手指离开时开启循环,即ACTION_UP

 @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                pauseLoop();
                break;
            case MotionEvent.ACTION_UP:
                if (mSes.isShutdown())
                    startLoop();
                break;
        }
        return false;
    }

至于循环播放的实现,是定义一个周期性的线程,让它循环自动操作,借助的是ScheduledExecutorService。下面是pauseLoop();startLoop()代码

protected void startLoop() {
        mSes = Executors.newSingleThreadScheduledExecutor();
        mSes.scheduleAtFixedRate(new AutoRunnable(), rate, rate, TimeUnit.SECONDS);
    }

    protected void pauseLoop() {
        mSes.shutdown();
    }

通过调用这两个方法来控制与实现循环轮播,原理就介绍到这里,下面来说下在项目中如何使用

使用

添加依赖

Maven

<dependency>
  <groupId>com.idisfkj.loopview</groupId>
  <artifactId>loopview</artifactId>
  <version>1.0.1</version>
  <type>pom</type>
</dependency>

Gradle

compile 'com.idisfkj.loopview:loopview:1.0.1'

根据自己的需求添加依赖

布局文件中引用

首先在根布局中加上自定义属性的引用

xmlns:loop="http://schemas.android.com/apk/res-auto"

引用LoopView控件

<com.idisfkj.loopview.LoopView
            android:id="@+id/loop_view"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            loop:bottom_style="@integer/loop_have_descript"
            loop:rate="3">
</com.idisfkj.loopview.LoopView>

bottom_style代表LoopView底部样式,有三个可选值,默认为loop_have_descript

  • loop_have_descript 代表有描述的布局

  • loop_no_descript_right 代表没有描述且圆点居右的布局

  • loop_no_descript_center 代表没有描述且圆点居中的布局

rate代表轮播的速度,单位为s,默认为3s

填充数据

填充数据需要借助LoopViewEntity实体类来存储,例如:

for (int i = 0; i < urls.length; i++) {
            LoopViewEntity entity = new LoopViewEntity();
            entity.setImageUrl(urls[i]);
            entity.setDescript(descripts[i]);
            list.add(entity);
        }
loopView.setLoopData(list);

item点击监听

loopView.setOnItemClickListener(new LoopView.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                //to do ...
            }
        });

欢迎Star与Fork,如有需要后续我会继续优化,或者加入与我一起来优化

项目地址:https://github.com/idisfkj/An...
个人blog:https://idisfkj.github.io