android viewpager轮播图滑到最后一页向左滑动跳到第一页,第一页向右滑动跳到最后一页
时间: 2023-08-27 11:03:47 浏览: 51
实现这个功能可以通过重写 ViewPager 的 `onPageSelected` 方法来实现,具体代码如下:
```
private int mCurrentPosition = 0;
private int mLastPosition = 0;
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// do nothing
}
@Override
public void onPageSelected(int position) {
// 记录当前位置和上一个位置
mLastPosition = mCurrentPosition;
mCurrentPosition = position;
// 最后一页向左滑动跳到第一页
if (mCurrentPosition == 0 && mLastPosition == (mAdapter.getCount() - 1)) {
viewPager.setCurrentItem(mCurrentPosition, false);
}
// 第一页向右滑动跳到最后一页
else if (mCurrentPosition == (mAdapter.getCount() - 1) && mLastPosition == 0) {
viewPager.setCurrentItem(mCurrentPosition, false);
}
}
@Override
public void onPageScrollStateChanged(int state) {
// do nothing
}
});
```
这里的 `mCurrentPosition` 表示当前位置,`mLastPosition` 表示上一个位置。在 `onPageSelected` 方法中,我们可以根据当前位置和上一个位置来判断是否需要进行页面跳转。如果当前位置是第一页,且上一个位置是最后一页,说明用户正在向左滑动最后一页,这时我们将当前位置跳转到第一页即可;同样的,如果当前位置是最后一页,且上一个位置是第一页,说明用户正在向右滑动第一页,这时我们将当前位置跳转到最后一页即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)