您需要像这样创建 PagerAdapter:
public class SamplePagerAdapter extends PagerAdapter{
List<View> pages = null;
public SamplePagerAdapter(List<View> pages){
this.pages = pages;
}
@Override
public Object instantiateItem(View collection, int position){
View v = pages.get(position);
((ViewPager) collection).addView(v, 0);
return v;
}
@Override
public void destroyItem(View collection, int position, Object view){
((ViewPager) collection).removeView((View) view);
}
@Override
public int getCount(){
return pages.size();
}
@Override
public boolean isViewFromObject(View view, Object object){
return view.equals(object);
}
@Override
public void finishUpdate(View arg0){
}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1){
}
@Override
public Parcelable saveState(){
return null;
}
@Override
public void startUpdate(View arg0){
}
}
然后创建fragmnet并将这样的代码放置到onCreateView
LayoutInflater inflater = LayoutInflater.from(this);
List<View> pages = new ArrayList<View>();
View page = inflater.inflate(R.layout.page, null);
TextView textView = (TextView) page.findViewById(R.id.text_view);
textView.setText("page1");
pages.add(page);
page = inflater.inflate(R.layout.page, null);
textView = (TextView) page.findViewById(R.id.text_view);
textView.setText("page2");
pages.add(page);
page = inflater.inflate(R.layout.page, null);
textView = (TextView) page.findViewById(R.id.text_view);
textView.setText("page 3");
pages.add(page);
SamplePagerAdapter pagerAdapter = new SamplePagerAdapter(pages);
ViewPager viewPager = new ViewPager(this);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(1);
setContentView(viewPager);
并创建一些界面来监听片段上的 ViewChange,并将当前页面通过界面传递给主要活动。这就是所有人:)