android最简单的ViewPager无限翻页

首先初始化一个视图集合,代码如下:

private void initlist() {
for (int i = 0; i < 5; i++) {
TextView v = new TextView(MainActivity.this);
v.setText("页面" + (i + 1));
v.setTextColor(0xFFFF0000);
v.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
list.add(v);
}
}


然后加载自定义适配器,定位在整型最大值的1/2,

viewpager.setAdapter(new Mypageradapter(list));
viewpager.setCurrentItem(Integer.MAX_VALUE/2);


适配器中count设为整型最大值

@Override
public int getCount() {
// TODO Auto-generated method stub
return Integer.MAX_VALUE;
}


关键代码,加载子视图时先判断该视图是否有父亲,如果有说明已被viewpager加载,那么用viewpager移除改视图,

@Override
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
ViewParent parent = list.get(position%list.size()).getParent();
if(parent!=null){
viewpager.removeView(list.get(position%list.size()));
}
container.addView(list.get(position%list.size()));
return list.get(position%list.size());
}


免费下载:http://download.csdn.net/detail/favouriter123/8186033


你可能感兴趣的:(android)