这适用于阵列在横幅轮播中保存横幅等情况的数组。用户单击两个导航按钮,如上一个和下一个。我的实现是:
public void onClick(View v) {
if (mCurrentIndex > 0) {mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;}
else {mCurrentIndex = mQuestionBank.length - 1;}
有更简单,更优雅的方法吗?
答案 0 :(得分:2)
我建议使用以下技巧。它只检查指针是否超出数组的边界并将其指向它的结尾或开始:
public int nextPrev(int mCurrentIndex, int direction) {
mCurrentIndex = mCurrentIndex + direction;
if(mCurrentIndex == mQuestionBank.length) {
mCurrentIndex = 0;
} else if (mCurrentIndex < 0) {
mCurrentIndex = mQuestionBank.length - 1;
}
return mCurrentIndex;
}
这将适用于direction = 1或-1。