LoopView-循环轮播控件


这次我们来学习一下日常看到的广告轮播器,几乎每个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

关注

clipboard.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
LoopView 是一个强大的轮转大图控件,并且提供了许多配置方法来达到您的显示效果和需求。github地址:https://github.com/xuehuayous/Android-LoopView介绍博客地址:http://blog.csdn.net/xuehuayous/article/details/50518393在项目中使用 LoopView如果您的项目使用 Gradle 构建, 只需要在您的build.gradle文件添加下面一行到 dependencies :    compile 'com.kevin:loopview:1.0.5'简单使用在layout.xml 中配置LoopView在Layout文件添加<com.kevin.loopview.AdLoopView<com.kevin.loopview.AdLoopView     android:id="@ id/main_act_adloopview"     android:layout_width="match_parent"     android:layout_height="192dp"> </com.kevin.loopview.AdLoopView>在代码中配置AdLoopView mLoopView = (AdLoopView) this.findViewById(R.id.main_act_adloopview); String json = LocalFileUtils.getStringFormAsset(this, "loopview_date.json"); // 使用 JsonTool 封装 JSON 数据到实体对象 LoopData loopData = JsonTool.toBean(json, LoopData.class); // 通过对象的方式设置数据 mLoopView.refreshData(loopData); // 开始轮转 mLoopView.startAutoLoop(); // 设置点击监听 mLoopView.setOnClickListener(new BaseLoopAdapter.OnItemClickListener() {         @Override         public void onItemClick(PagerAdapter parent, View view,              int position, int realPosition) {             // 获取数据             LoopData loopData = mLoopView.getLoopData();             String url = loopData.items.get(position).link;             // 通过系统浏览器打开跳转链接             Intent intent = new Intent();             intent.setData(Uri.parse(url));             intent.setAction(Intent.ACTION_VIEW);             startActivity(intent);         }     });更多配置XML 配置在XML中使用AdLoopView,可以有如下配置:<com.kevin.loopview.AdLoopView     android:id="@ id/adloop_act_adloopview"     android:layout_width="match_parent"     android:layout_height="192dp"     kevin:loop_interval="5000"     kevin:loop_dotMargin="5dp"     kevin:loop_autoLoop="[true|false]"     kevin:loop_dotSelector="@drawable/ad_dots_selector"     kevin:loop_layoutId="@layout/ad_loopview_layout"> </com.kevin.loopview.AdLoopView>在代码中配置// 设置ViewPager页面切换时间 mLoopView.setScrollDuration(1000); // 设置轮转时间间隔 mLoopView.setInterval(3000); // 以集合的方式初始化数据 mLoopView.setLoopViewPager(List<Map<String, String>> data); // 以JSON的方式初始化数据 mLoopView.setLoopViewPager(String jsonData); // 以数据实体的方式初始化数据 mLoopView.setLoopViewPager(LoopData rotateData); // 以集合的方式刷新数据 mLoopView.refreshData(final List<Map<String, String>> data); // 以数据实体的方式刷新数据 mLoopView.refreshData(LoopData loopData); // 以JSON的方式刷新数据 mLoopView.refreshData(String jsonData); // 获取配置的轮转大图数据 mLoopView.getLoopData(); // 开始自动轮转 mLoopView.startAutoLoop(); // 在指定时间延迟后自动轮转 mLoopView.startAutoLoop(long delayTimeInMills); // 停止自动轮转 mLoopView.stopAutoLoop(); // 设置自定义布局 mLoopView.setLoopLayout(int layoutResId);

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值