ViewPager的适配器有PagerAdapter、FragmentPagerAdapter、FragmentStatePagerAdapter。
重写PagerAdapter的时候注意以下:
getCount():返回ViewPager的长度
destroyItem(ViewGroup container, int position, Object object):销毁是调用
instantiateItem(ViewGroup container, final int position):创建当前position时调用
isViewFromObject(View arg0, Object arg1):不知道有什么用
给ViewPager添加非Fragment的时候用PagerAdapter会更加好一些,由于之前重写过类似的,就没翻以前的代码直接写了,但是写完之后测试出现了一个莫名其妙的问题,设置的ViewPager长度为5,但是只有第一页上添加到了内容,其他页啥也不显示。我就*了狗了。如下代码:
public class MyAdapter extends PagerAdapter { List<TextView> mImageViews; public FolderGroupAdapter(List<TextView> list) { this.mImageViews = list; } @Override public int getCount() { // TODO Auto-generated method stub return mImageViews.size(); } @Override public boolean isViewFromObject(View arg0, Object arg1) { // TODO Auto-generated method stub return arg0 == arg1; } @Override public void destroyItem(ViewGroup container, int position, Object object) { // TODO Auto-generated method stub container.removeView(mImageViews.get(position)); } @Override public Object instantiateItem(ViewGroup container, final int position) { TextView mView = mImageViews.get(position); try { container.addView(mView); } catch (Exception e) { // handler something } return mImageViews.get(position); } }
初始化:
TextView views = (TextView) mInflater.from(this).inflate(R.layout.texttextview, null);; List<TextView> list = new ArrayList<TextView>(); for (int i = 0; i < 5; i++) { list.add(views); } MyAdapter adapter = new MyAdapter(list); pager.setAdapter(adapter);
折腾了半天,发现是在这里出错了:
TextView views=null; List<TextView> list = new ArrayList<TextView>(); for (int i = 0; i < 5; i++) { views = (TextView) mInflater.from(this).inflate(R.layout.texttextview, null); list.add(views); } MyAdapter adapter = new MyAdapter(list); pager.setAdapter(adapter);
呃,看似不是问题的问题,浪费时间啊。