Android实现ViewPager无限循环滚动回绕
Android实现ViewPager无限循环滚动回绕
Android系统提供的ViewPager标准方式是左右可以自由滑动,但是滑动到最左边的极限位置是第一个page,滑动到最右边的位置是最后一个page,当滑动到最左或者最右时候,就不能再滑动/滚动了,这是Android系统默认的ViewPager实现方式。
但是有些情况下开发者可能希望ViewPager能够智能的无限循环滚动回绕,比如现在总共有编号1, 2, 3, 4, 5的5个Page。
(1)当用户手指从右往左滚动到最右边/最后面的页面5时候,如果此时用户继续拖住ViewPager往左边滑动,那么ViewPager将回绕、循环到第一个Page -> 1,接着就是2,3,4,5;
(2)反过来,如果当用户手指从左往右,滑到最左边的第一个Page:1时候,如果此时继续拖住ViewPager继续从左往右滑动,那么将回绕到5,接着就是4,3,2,1.
我们把这种ViewPager称之谓“无限循环滚动回绕”的ViewPager。
这种类型的ViewPager网上有较多实现方式,现在给出一个流程较广的代码实现。
写一个测试的MainActivity.java:
package zhangphil.demo; import java.util.Random; import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoopViewPager viewpager = (LoopViewPager) findViewById(R.id.viewpager);
viewpager.setAdapter(new SamplePagerAdapter());
} public class SamplePagerAdapter extends PagerAdapter {
private final Random random = new Random();
private int mSize; public SamplePagerAdapter() {
mSize = 5;
} public SamplePagerAdapter(int count) {
mSize = count;
} @Override
public int getCount() {
return mSize;
} @Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
} @Override
public void destroyItem(ViewGroup view, int position, Object object) {
view.removeView((View) object);
} @Override
public Object instantiateItem(ViewGroup view, int position) {
TextView textView = new TextView(view.getContext()); textView.setText(position + 1 + "");
textView.setBackgroundColor(0xff000000 | random.nextInt(0x00ffffff));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(Color.WHITE);
textView.setTextSize(50);
view.addView(textView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); return textView;
} // 增加item
public void addItem() {
mSize++;
notifyDataSetChanged();
} // 删除item
public void removeItem() {
mSize--;
mSize = mSize < 0 ? 0 : mSize; notifyDataSetChanged();
}
}
}
MainActivity.java需要的布局文件activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="zhangphil.demo.MainActivity" > <zhangphil.demo.LoopViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
核心关键代码LoopViewPager.java类和LoopViewPager.java依赖的LoopPagerAdapterWrapper.java!
LoopViewPager.java:
package zhangphil.demo; import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import java.util.ArrayList;
import java.util.List; public class LoopViewPager extends ViewPager {
private static final boolean DEFAULT_BOUNDARY_CASHING = false;
private static final boolean DEFAULT_BOUNDARY_LOOPING = true; private LoopPagerAdapterWrapper mAdapter;
private boolean mBoundaryCaching = DEFAULT_BOUNDARY_CASHING;
private boolean mBoundaryLooping = DEFAULT_BOUNDARY_LOOPING;
private List<OnPageChangeListener> mOnPageChangeListeners; /**
* helper function which may be used when implementing FragmentPagerAdapter
*
* @return (position-1)%count
*/
public static int toRealPosition(int position, int count) {
position = position - 1;
if (position < 0) {
position += count;
} else {
position = position % count;
}
return position;
} /**
* If set to true, the boundary views (i.e. first and last) will never be
* destroyed This may help to prevent "blinking" of some views
*/
public void setBoundaryCaching(boolean flag) {
mBoundaryCaching = flag;
if (mAdapter != null) {
mAdapter.setBoundaryCaching(flag);
}
} public void setBoundaryLooping(boolean flag) {
mBoundaryLooping = flag;
if (mAdapter != null) {
mAdapter.setBoundaryLooping(flag);
}
} @Override
public void setAdapter(PagerAdapter adapter) {
mAdapter = new LoopPagerAdapterWrapper(adapter);
mAdapter.setBoundaryCaching(mBoundaryCaching);
mAdapter.setBoundaryLooping(mBoundaryLooping);
super.setAdapter(mAdapter);
setCurrentItem(0, false);
} @Override
public PagerAdapter getAdapter() {
return mAdapter != null ? mAdapter.getRealAdapter() : mAdapter;
} @Override
public int getCurrentItem() {
return mAdapter != null ? mAdapter.toRealPosition(super.getCurrentItem()) : 0;
} public void setCurrentItem(int item, boolean smoothScroll) {
int realItem = mAdapter.toInnerPosition(item);
super.setCurrentItem(realItem, smoothScroll);
} @Override
public void setCurrentItem(int item) {
if (getCurrentItem() != item) {
setCurrentItem(item, true);
}
} @Override
public void setOnPageChangeListener(OnPageChangeListener listener) {
addOnPageChangeListener(listener);
} @Override
public void addOnPageChangeListener(OnPageChangeListener listener) {
if (mOnPageChangeListeners == null) {
mOnPageChangeListeners = new ArrayList<>();
}
mOnPageChangeListeners.add(listener);
} @Override
public void removeOnPageChangeListener(OnPageChangeListener listener) {
if (mOnPageChangeListeners != null) {
mOnPageChangeListeners.remove(listener);
}
} @Override
public void clearOnPageChangeListeners() {
if (mOnPageChangeListeners != null) {
mOnPageChangeListeners.clear();
}
} public LoopViewPager(Context context) {
super(context);
init(context);
} public LoopViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
} private void init(Context context) {
if (onPageChangeListener != null) {
super.removeOnPageChangeListener(onPageChangeListener);
}
super.addOnPageChangeListener(onPageChangeListener);
} private OnPageChangeListener onPageChangeListener = new OnPageChangeListener() {
private float mPreviousOffset = -1;
private float mPreviousPosition = -1; @Override
public void onPageSelected(int position) { int realPosition = mAdapter.toRealPosition(position);
if (mPreviousPosition != realPosition) {
mPreviousPosition = realPosition; if (mOnPageChangeListeners != null) {
for (int i = 0; i < mOnPageChangeListeners.size(); i++) {
OnPageChangeListener listener = mOnPageChangeListeners.get(i);
if (listener != null) {
listener.onPageSelected(realPosition);
}
}
}
}
} @Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int realPosition = position;
if (mAdapter != null) {
realPosition = mAdapter.toRealPosition(position); if (positionOffset == 0 && mPreviousOffset == 0
&& (position == 0 || position == mAdapter.getCount() - 1)) {
setCurrentItem(realPosition, false);
}
} mPreviousOffset = positionOffset; if (mOnPageChangeListeners != null) {
for (int i = 0; i < mOnPageChangeListeners.size(); i++) {
OnPageChangeListener listener = mOnPageChangeListeners.get(i);
if (listener != null) {
if (realPosition != mAdapter.getRealCount() - 1) {
listener.onPageScrolled(realPosition, positionOffset, positionOffsetPixels);
} else {
if (positionOffset > .5) {
listener.onPageScrolled(0, 0, 0);
} else {
listener.onPageScrolled(realPosition, 0, 0);
}
}
}
}
}
} @Override
public void onPageScrollStateChanged(int state) {
if (mAdapter != null) {
int position = LoopViewPager.super.getCurrentItem();
int realPosition = mAdapter.toRealPosition(position);
if (state == ViewPager.SCROLL_STATE_IDLE && (position == 0 || position == mAdapter.getCount() - 1)) {
setCurrentItem(realPosition, false);
}
} if (mOnPageChangeListeners != null) {
for (int i = 0; i < mOnPageChangeListeners.size(); i++) {
OnPageChangeListener listener = mOnPageChangeListeners.get(i);
if (listener != null) {
listener.onPageScrollStateChanged(state);
}
}
}
}
};
}
LoopPagerAdapterWrapper.java:
package zhangphil.demo; import android.os.Parcelable;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup; public class LoopPagerAdapterWrapper extends PagerAdapter { private PagerAdapter mAdapter; private SparseArray<ToDestroy> mToDestroy = new SparseArray<>(); private static final boolean DEFAULT_BOUNDARY_CASHING = true;
private static final boolean DEFAULT_BOUNDARY_LOOPING = true; private boolean mBoundaryCaching = DEFAULT_BOUNDARY_CASHING;
private boolean mBoundaryLooping = DEFAULT_BOUNDARY_LOOPING; void setBoundaryCaching(boolean flag) {
mBoundaryCaching = flag;
} void setBoundaryLooping(boolean flag) {
mBoundaryLooping = flag;
} LoopPagerAdapterWrapper(PagerAdapter adapter) {
this.mAdapter = adapter;
} @Override
public void notifyDataSetChanged() {
mToDestroy = new SparseArray<>();
super.notifyDataSetChanged();
} int toRealPosition(int position) {
int realPosition = position;
int realCount = getRealCount();
if (realCount == 0)
return 0;
if (mBoundaryLooping) {
realPosition = (position - 1) % realCount;
if (realPosition < 0)
realPosition += realCount;
} return realPosition;
} public int toInnerPosition(int realPosition) {
int position = (realPosition + 1);
return mBoundaryLooping ? position : realPosition;
} private int getRealFirstPosition() {
return mBoundaryLooping ? 1 : 0;
} private int getRealLastPosition() {
return getRealFirstPosition() + getRealCount() - 1;
} @Override
public int getCount() {
int count = getRealCount();
return mBoundaryLooping ? count + 2 : count;
} public int getRealCount() {
return mAdapter.getCount();
} public PagerAdapter getRealAdapter() {
return mAdapter;
} @Override
public Object instantiateItem(ViewGroup container, int position) {
int realPosition = (mAdapter instanceof FragmentPagerAdapter || mAdapter instanceof FragmentStatePagerAdapter)
? position : toRealPosition(position); if (mBoundaryCaching) {
ToDestroy toDestroy = mToDestroy.get(position);
if (toDestroy != null) {
mToDestroy.remove(position);
return toDestroy.object;
}
}
return mAdapter.instantiateItem(container, realPosition);
} @Override
public void destroyItem(ViewGroup container, int position, Object object) {
int realFirst = getRealFirstPosition();
int realLast = getRealLastPosition();
int realPosition = (mAdapter instanceof FragmentPagerAdapter || mAdapter instanceof FragmentStatePagerAdapter)
? position : toRealPosition(position); if (mBoundaryCaching && (position == realFirst || position == realLast)) {
mToDestroy.put(position, new ToDestroy(container, realPosition, object));
} else {
mAdapter.destroyItem(container, realPosition, object);
}
} /*
* Delegate rest of methods directly to the inner adapter.
*/ @Override
public void finishUpdate(ViewGroup container) {
mAdapter.finishUpdate(container);
} @Override
public boolean isViewFromObject(View view, Object object) {
return mAdapter.isViewFromObject(view, object);
} @Override
public void restoreState(Parcelable bundle, ClassLoader classLoader) {
mAdapter.restoreState(bundle, classLoader);
} @Override
public Parcelable saveState() {
return mAdapter.saveState();
} @Override
public void startUpdate(ViewGroup container) {
mAdapter.startUpdate(container);
} @Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
mAdapter.setPrimaryItem(container, position, object);
} /*
* End delegation
*/ /**
* Container class for caching the boundary views
*/
static class ToDestroy {
ViewGroup container;
int position;
Object object; public ToDestroy(ViewGroup container, int position, Object object) {
this.container = container;
this.position = position;
this.object = object;
}
}
}
如果读者有兴趣使用,直接将上面两个核心关键代码放入到自己的项目代码包中,当作自己写的类直接使用即可,写布局时候不要再写ViewPager,而是直接像我上面写的那个布局文件一样用LoopViewPager。
Android实现ViewPager无限循环滚动回绕的更多相关文章
- 详细分析Android viewpager 无限循环滚动图片
由于最近在忙于项目,就没时间更新博客了,于是趁着周日在房间把最近的在项目中遇到的技术总结下.最近在项目中要做一个在viewpager无限滚动图片的需求,其实百度一下有好多的例子,但是大部分虽然实现了, ...
- 一行代码引入 ViewPager 无限循环 + 页码显示
(出处:http://www.cnblogs.com/linguanh) 前序: 网上的这类 ViewPager 很多,但是很多都不够好,体现在 bug多.对少页面不支持,例如1~2张图片.功能整合不 ...
- unity 背景无限循环滚动效果
背景无限循环滚动效果如下示: 步骤如下: 导入背景图片后,设置图片的格式,如下图: 2.图片格式也可以设置是Texture格式,但是Wrap Mode 一定要是Repeat[重复发生]:然后记得App ...
- 封装一个ViewPager真正的实现图片无限循环滚动带导航点
效果图: 大家在写项目的过程中常常会碰到须要实现Viewpager里面载入几张图片来循环自己主动轮播的效果,假设不封装一下的话代码分散在activity里面会显得非常乱.并且也不利于我们下次复用,所以 ...
- ViewPager 无限循环
Overview 我们在使用ViewPager来制作图片轮播的时候,常常为ViewPager不能一直无限循环的问题所苦恼.对于这个问题,目前从网上找到了两个思路来解决: 将 ViewPager 的Co ...
- iOS无限循环滚动scrollview
经常有园友会问"博主,有没有图片无限滚动的Demo呀?", 正儿八经的图片滚动的Demo我这儿还真没有,今天呢就封装一个可以在项目中直接使用的图片轮播.没看过其他iOS图片无限轮播 ...
- Cocos2dx中利用双向链表实现无限循环滚动层
[Qboy原创] 在Cocos2dX 3.0 中已经实现一些牛逼的滚动层,但是对于有一些需要实现循环滚动的要求确没有实现,笔者在前段时间的一个做了一个游戏,需求是实现在少有的(13个)英雄中进行循环滚 ...
- ViewPager 无限循环遇到的坑 viewpager.setOffscreenPageLimit(2);
viewpager.setOffscreenPageLimit(limit);这个方法,是表示viewpage除了当前显示的页面外,左右个预加载的页面个数,也就是 为limit=2时表示当前一共加载了 ...
- viewpager双层嵌套,子viewpager无限循环无法手动滑动
项目中首页是用viewpager+fragment集成的,第一个fragment有广告轮播图使用viewpager实现的,开始就遇到是广告图无法手动滑动,事件被外层的viewpager拦截响应切换到下 ...
随机推荐
- webview 播放H5视频问题 黑屏 只有声音没有画面
android 用webview 播放网络视频怎控制播放按键? 在代码中加入webview.getSettings().setJavaScriptEnabled(true);//支持jswebview ...
- 转 linux/unix学习经典书籍
都是一些链接. 1. Linux网络编程经典书籍推荐 http://blog.csdn.net/zhangpeng_linux/article/details/7001970 2. C语言经典著作导读 ...
- git ldap
https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/README.md ldap : enabled : true host : 'ope ...
- 快速访问GitHub
Github网站可以访问,但是由于网络代理商的原因,造成访问速度很慢. 本文采取方法:手动更改hosts Hosts是一个没有扩展名的系统文件,可以用记事本等工具打开,其作用就是将一些常用的网址域名与 ...
- ubuntu 16.04 Hbase 安装
1.解压安装包至路径 /usr/local 1.1.sudo tar -zxf ~/下载/hbase-1.1.2-bin.tar.gz -C /usr/local 2.将解压的文件名hbase-1.1 ...
- java动态代理实例
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflec ...
- jeesite ckfinder mac/linux 文件上传路径设置
背景: 如果你使用的是Mac 或者 Ubuntu 这种 Unix系统的话,你一定知道Unix系统的文件路径分隔符是 / 而Windows系统文件分隔符是 \ 当你设置了jeesite.properti ...
- PCB genesis短槽加引导孔实现方法
一.何为短槽 短槽通常定义:槽长小于2倍槽宽 如:槽长1.8mm,槽宽1.0mm 二.为什么要加短槽加引孔呢 短槽孔在钻孔时孔易偏斜导致槽长偏短, 当槽长宽比越小,则受力越不均匀,在钻第2个 ...
- 洛谷P1613 跑路(最短路+倍增)
P1613 跑路 题目描述 小A的工作不仅繁琐,更有苛刻的规定,要求小A每天早上在6:00之前到达公司,否则这个月工资清零.可是小A偏偏又有赖床的坏毛病.于是为了保住自己的工资,小A买了一个十分牛B的 ...
- Django day25 序列化组件(*****)
序列化:将变量从内存中存储或传输的过程称之为序列化 1.序列化组件是干什么用的? 对应着表,写序列化的类 2.如何使用序列化组件 Serializer 1) 重命名:用source:xx = seri ...