我正在显示仅包含ImageViews的ViewPager。但是,我需要它以循环方式不断发生。对于Ex:... c> B> A> B> ç...
答案 0 :(得分:2)
只需实现ViewPager.OnPageChangeListener:
YOUR_VIEWPAGER.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
currentPage = position;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// not needed
}
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
int pageCount = pages.size();
if (currentPage == 0){
YOUR_VIEWPAGER.setCurrentItem(pageCount-2,false);
} else if (currentPage == pageCount-1){
YOUR_VIEWPAGER.setCurrentItem(1,false);
}
}
}
});
答案 1 :(得分:0)
尝试这个。它将得到类似C <-> A <-> B <-> C <-> A
的结果viewPager?.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
var currentPage : Int = 0
var mPreviousPosition : Int = 0
var mIsEndOfCycle = false
override fun onPageScrollStateChanged(state: Int) {
val pageCount = viewPager?.adapter?.count
if (state == ViewPager.SCROLL_STATE_IDLE) {
if (mPreviousPosition == currentPage && !mIsEndOfCycle) {
if (currentPage == 0) {
pageCount?.minus(1)?.let { viewPager?.setCurrentItem(it, false) };
} else {
viewPager?.setCurrentItem(0, false);
}
mIsEndOfCycle = true;
} else {
mIsEndOfCycle = false;
}
mPreviousPosition = currentPage;
}
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
override fun onPageSelected(position: Int) {
currentPage = position
}
})
答案 2 :(得分:0)
以下为我做了。我不希望用户从第一页“返回”到最后一页。所以基本上我有三个不同的屏幕,但实际上我在适配器中有四个,像这样:A -> B -> C -> A。当用户点击第二个“A”页面时,寻呼机状态变为空闲,我无缝切换到第一个“A”页。我什至有一个页面指示器,我已经类似地覆盖了它。
val pageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrollStateChanged(state: Int) {
super.onPageScrollStateChanged(state)
if (state == ViewPager.SCROLL_STATE_IDLE) {
if (viewPager.currentItem == NUM_PAGES - 1) {
viewPager.setCurrentItem(0, false)
}
}
}
}