ViewPager 是不能循环滚动的,但是在项目中可能需要用到循环滚动的 ViewPager,比如广告栏。下面介绍循环 ViewPager 的两种实现方式。
方法1:将 count 设为尽可能的大,制造一种假的循环。
这是网上出现比较多的方法,实现起来较为简单。需要注意的是,我们需要设置 ViewPager 的初始 position,否则第一页无法向右滑动。直接看代码。
public class MainActivity extends Activity {
private List views = new ArrayList();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 省略初始化 views ...
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new MyPagerAdapter1());
// 设置当前 position,为views.size() 整数倍。
int firstPage = Integer.MAX_VALUE / 2 / views.size() * views.size();
viewPager.setCurrentItem(firstPage, false);
}
class MyPagerAdapter1 extends PagerAdapter {
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
int index = innerPosition(position);
container.addView(views.get(index));
return views.get(index);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
int index = innerPosition(position);
container.removeView(views.get(index));
}
private int innerPosition(int position) {
return position % views.size();
}
}
}
方法2: 在 ViewPager 的首尾添加一个重复的 View
这是一种真正的无限循环。在 ViewPager 的首尾多添加一个 View,监听 ViewPager 滚动事件,当滑到边界时,设置当前 position 为中间的某个 item,当然,它们的内容必须是一样的。不过这种方式容易出现页面闪动导致滑动不连贯,这是因为 ViewPager#setCurrentItem(item)
是需要时间来完成测量及绘制的,但我们可以用一些技巧来达到平滑过渡。
核心代码:为 ViewPager 添加一个滚动监听 CycleScrollOnPageChangeListener
。
class CycleScrollOnPageChangeListener implements OnPageChangeListener {
@Override
public void onPageSelected(int arg0) {
}
@Override
public void onPageScrolled(int position, float offset, int offsetPixels) {
// 检测是否达到首页或者尾页
if (offset == 0) {
if (position == 0) {
viewPager.setCurrentItem(views.size() - 2, false);
} else if (position == (views.size() - 1)) {
viewPager.setCurrentItem(1, false);
}
}
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
}
完整代码如下:
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
private int[] drawableIds = new int[] { R.drawable.koala, R.drawable.desert,
R.drawable.hydrangeas, R.drawable.jellyfish };
private ViewPager viewPager;
private List views = new ArrayList();
private List drawableList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewpager);
initData();
createPageItems();
viewPager.setAdapter(new MyPagerAdapter());
viewPager.addOnPageChangeListener(new CycleScrollOnPageChangeListener());
// 当滑到第0页时,position 会设置到 views.size() - 2
// 先对其初始化,防止 setCurrentItem 因为时间延迟而出现闪动
viewPager.setCurrentItem(views.size() - 2, false);
viewPager.setVisibility(View.INVISIBLE);
viewPager.postDelayed(new Runnable() {
@Override
public void run() {
viewPager.setVisibility(View.VISIBLE);
// 设置初始 position
viewPager.setCurrentItem(1, false);
}
}, 100);
}
private void initData() {
drawableList = new ArrayList();
drawableList.add(drawableIds[drawableIds.length - 1]);
for (int id : drawableIds) {
drawableList.add(id);
}
drawableList.add(drawableIds[0]);
}
private void createPageItems() {
LayoutInflater inflater = LayoutInflater.from(this);
for (int i = 0; i < drawableList.size(); i++) {
View view = inflater.inflate(R.layout.viewpager_item, null);
views.add(view);
}
}
class CycleScrollOnPageChangeListener implements OnPageChangeListener {
@Override
public void onPageSelected(int arg0) {
}
@Override
public void onPageScrolled(int position, float offset, int offsetPixels) {
if (offset == 0) {
if (position == 0) {
viewPager.setCurrentItem(views.size() - 2, false);
} else if (position == (views.size() - 1)) {
viewPager.setCurrentItem(1, false);
}
}
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
}
class MyPagerAdapter extends PagerAdapter {
@Override
public int getCount() {
return views.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = views.get(position);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
imageView.setImageResource(drawableList.get(position));
TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setText(String.valueOf(position));
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(views.get(position));
}
}
}
布局文件:activity_main 就只有一个 ViewPager。 ViewPager 的item 布局为 viewpager_item,如下所示。
自动循环滚动的实现
以上这些方法还不能让 ViewPager 做到自动循环滚动,如果需要自动滚动的话,只需用一个 Handler 不断的轮询去设置 ViewPager 的当前 position 即可。同时还需要监听 ViewPager 的触摸事件,当用户想自己滚动的时候,停止自动滚动。代码如下:
Handler 实现一个定时器
private Handler handler = new Handler();
private boolean stopAutoScroll = false;
private Runnable autoScrollRunnable = new Runnable() {
@Override
public void run() {
if (!stopAutoScroll) {
int currentItem = viewPager.getCurrentItem();
viewPager.setCurrentItem(currentItem + 1, true);
handler.postDelayed(autoScrollRunnable, 4000);
}
}
};
在 onCreate 里面 handler 发送消息开始滚动(在onResume开始滚动,onPause停止滚动更好),并在用户 touch_down 的时候停止滚动。
handler.postDelayed(autoScrollRunnable, 4000);
viewPager.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
stopAutoScroll = true;
handler.removeCallbacks(autoScrollRunnable);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
stopAutoScroll = false;
handler.postDelayed(autoScrollRunnable, 4000);
break;
}
return false;
}
});
最后不要忘了在 onDestroy 移除消息防止内存泄漏handler.removeCallbacks(autoScrollRunnable);