RecyclerView 实现轮播图

来源:互联网 发布:易语言安装包源码 编辑:程序博客网 时间:2024/06/05 16:14

有的同学很想实现自己的轮播图  但是却弄了一通放弃了   现在RecyclerView出现之后 很多同学就可以放心了  他有个非常棒的方法  能够像ViewPager一样 单页横向切换,且滑动到一半 或者一部分    自动滑动回去 或者 滑向下一页

Support RecyclerView 24.2.0中增加一个非常重要的类SnapHelper,他的作用是让RecyclerView滑动视图后使停止位置正好停在某页的正中间。使用方式很简单
重点在于new LinearSnapHelper().attachToRecyclerView(recyclerView);

LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);recyclerView.setLayoutManager(linearLayoutManager);new LinearSnapHelper().attachToRecyclerView(recyclerView);
关键就是这个linearSnapHelper
无限滑动就是 将 apdater的getCount()方法中的  返回值 调整Integer.MAX_VALUE
接着就是让他定时滑动了  定时滑动 无非就是利用handler定时发送一个消息 然后滑动
private Handler handler = new Handler() {    @Override    public void handleMessage(Message msg) {        super.handleMessage(msg);        switch (msg.what) {            case SCROLL_WHAT:                if (getLayoutManager() instanceof LinearLayoutManager && getAdapter() != null) {                    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getLayoutManager();                        int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();                        int adapterSize = getAdapter().getItemCount();                        if (adapterSize < 2) return;//这里 count大于等于2个才开始轮播                        if (lastVisibleItemPosition >= (adapterSize - 1)) {                            smoothScrollToPosition(0);                        } else {                            smoothScrollToPosition(lastVisibleItemPosition + 1);                        }                       
handler.sendEmptyMessageDelayed(SCROLL_WHAT, 1500);
} break; } }};
当然如果用户 手指在轮播图上了  要停止滑动了 这个就要监听onTouch事件了
private RecyclerView.OnItemTouchListener onItemTouchListener = new OnItemTouchListener() {    @Override    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {        int action = MotionEventCompat.getActionMasked(e);            if ((action == MotionEvent.ACTION_DOWN)) {
//当按下无非就是  移除消息 来停止滑动
handler.removeMessages(SCROLL_WHAT);
} else if (e.getAction() == MotionEvent.ACTION_UP) {
//当手指抬起是  再次发送消息 来 使轮播图重新滚动起来
handler.sendEmptyMessageDelayed(SCROLL_WHAT, delayTimeInMills);
} return false; }
 @Override    
public void onTouchEvent(RecyclerView rv, MotionEvent e) {    }    
@Override    
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {    }};



原创粉丝点击