@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager)container).removeView(mImageViews[position % mImageViews.length]);
}
/**
* 载入图片进去,用当前的position 除以 图片数组长度取余数是关键
*/
@Override
public Object instantiateItem(View container, int position) {
((ViewPager)container).addView(mImageViews[position % mImageViews.length], 0);
return mImageViews[position % mImageViews.length];
}
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int arg0) {
setImageBackground(arg0 % mImageViews.length);
}
/**
* 设置选中的tip的背景
* @param selectItems
*/
private void setImageBackground(int selectItems){
for(int i=0; i<tips.length; i++){
if(i == selectItems){
tips[i].setBackgroundResource(R.drawable.page_indicator_focused);
}else{
tips[i].setBackgroundResource(R.drawable.page_indicator_unfocused);
}
}
}
}
上面的代码中,当只有3张图片或者2张图片的时候,滑动存在BUG问题的修改如下
destroyItem(View container, int position, Object object)方法中不removeView
@Override
public void destroyItem(View container, int position, Object object) {
// ((ViewPager)container).removeView(mImageViews[position % mImageViews.length]);
}
instantiateItem(View container, int position)增加异常扑捉
@Override
public Object instantiateItem(View container, int position) {
try {
((ViewPager)container).addView(mImageViews[position % mImageViews.length], 0);
}catch(Exception e){
//handler something
}
return mImageViews[position % mImageViews.length];
}
Android 使用ViewPager实现左右循环滑动图片DEMO代码下载
具体下载目录在 /2014年资料/2月/27日/Android 使用ViewPager实现左右循环滑动图片