Closed
Description
在android上使用slider组件时,且数据个数为2时,设置slider的index为0之后,slider的index会变成1,且无法循环滚动,效果如下所示:
slider中的元素在切换到第一个之后,突然会跳到第二个。其原因跟WXCircleViewPager中的 _setCurrentItem()_函数的代码有关:
public void setCurrentItem(int item, boolean smoothScroll) {
if (getAdapter().getCount() == 0) {
super.setCurrentItem(item, smoothScroll);
return;
}
item = getOffsetAmount() + (item % getAdapter().getCount());
super.setCurrentItem(item, smoothScroll);
}
此函数调用的_getOffsetAmount()_返回的结果会用当前元素的个数乘以50:
private int getOffsetAmount() {
if (getAdapter().getCount() == 0) {
return 0;
}
if (getAdapter() instanceof WXCirclePageAdapter) {
WXCirclePageAdapter infAdapter = (WXCirclePageAdapter) getAdapter();
// allow for 100 back cycles from the beginning
// should be enough to create an illusion of infinity
// warning: scrolling to very high values (1,000,000+) results in
// strange drawing behaviour
return infAdapter.getRealCount() * 50;
} else {
return 0;
}
}
由于adapter中的元素个数为2,该函数返回的结果为100. 而ViewPager类的设置显示元素的index的代码如下:
void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) {
if (mAdapter == null || mAdapter.getCount() <= 0) {
setScrollingCacheEnabled(false);
return;
}
if (!always && mCurItem == item && mItems.size() != 0) {
setScrollingCacheEnabled(false);
return;
}
if (item < 0) {
item = 0;
} else if (item >= mAdapter.getCount()) {
item = mAdapter.getCount() - 1;
}
......
}
此时的item为100, 而adapter中的_getCount()_返回的值为2:
public int getCount() {
// if count less than 3,the circle doesn't work as expected.
int count = getRealCount();
if (count > 2) {
return count * 110;
} else {
return count;
}
}
故item的值会被设置成1. 可见,slider控件为了实现循环滚动效果,对2个元素做了特殊处理, 只需对_WXCircleViewPager_的函数进行如下修改即可:
private int getOffsetAmount() {
if (getAdapter().getCount() == 0) {
return 0;
}
if (getAdapter() instanceof WXCirclePageAdapter) {
WXCirclePageAdapter infAdapter = (WXCirclePageAdapter) getAdapter();
// allow for 100 back cycles from the beginning
// should be enough to create an illusion of infinity
// warning: scrolling to very high values (1,000,000+) results in
// strange drawing behaviour
int realCount = infAdapter.getRealCount();
return realCount> 2 ? realCount * 50 : 0;
} else {
return 0;
}
}
Metadata
Metadata
Assignees
Labels
No labels