Activity代码
public class MainActivity extends AppCompatActivity { private List<View> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); list= new ArrayList<View>(); /** * 通过view对象作为viewpager的数据源 */ View view1=View.inflate(this,R.layout.view1,null); View view2=View.inflate(this,R.layout.view2,null); View view3=View.inflate(this,R.layout.view3,null); View view4=View.inflate(this,R.layout.view4,null); list.add(view1); list.add(view2); list.add(view3); list.add(view4); //创建pageadapter Mypageadapter mypageadapter= new Mypageadapter(list); //初始化viewpager ViewPager pager= (ViewPager)findViewById(R.id.viewpager); //加载适配器 pager.setAdapter(mypageadapter); } }
总体的思路是创建一个View的list集合,通过inflate方法将页面转化为view,初始化list并添加view为元素,初始化viewpager并加载适配器
pageradapter代码
public class Mypageadapter extends PagerAdapter { private List<View> viewList; public Mypageadapter(List<View>viewList){ this.viewList=viewList; } //返回页卡的数量 @Override public int getCount() { return viewList.size(); } //page是否来自于对象 @Override public boolean isViewFromObject(View view, Object object) { return view==object; } /* * 实例化一个页卡 * */ @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(viewList.get(position)); return viewList.get(position); } //销毁一个页卡 @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(viewList.get(position)); } }
继承pageradapter方法,创建一个有参的构造方法,在Activity中调用时将LIstVIew传递进来
除了实现的两个方法之外还要实现一个初始化页卡的方法和另一个销毁页卡的方法