###布局自定义3个item
### MainActivity
public class MainActivity extends Activity {
List<View> list=new ArrayList<View>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获得viewpager要显示的页面
getView();
//找到ViewPager控件
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(new MyPagerAdapter(list));
//设置初始的页面
viewPager.setCurrentItem(2);
}
/**
* //获得viewpager要显示的页面
*/
private void getView() {
View view1 = View.inflate(this, R.layout.item1, null);
View view2 = View.inflate(this, R.layout.item2, null);
View view3 = View.inflate(this, R.layout.item3, null);
/* Button button =(Button) view3.findViewById(R.id.button);
//点击页面3里的按钮,跳转到新的activity
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, SecondActivity.class));
}
});*/
list.add(view1);
list.add(view2);
list.add(view3);
}
}
###MyPagerAdapter适配器
public class MyPagerAdapter extends PagerAdapter {
List<View> list;
public MyPagerAdapter(List<View> list){
this.list=list;
}
@Override//viewpager的总条目
public int getCount() {
return list.size();
}
@Override//实例化每一个条目
public Object instantiateItem(ViewGroup container, int position) {
//按position取出集合里的view
View view = list.get(position);
//把view装进容器
container.addView(view);
return view;
}
@Override//判断当前的视图是不是instantiateItem实例化的
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0==arg1;
}
@Override//销毁条目
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
// super.destroyItem(container, position, object);
//销毁条目
container.removeView((View) object);
}
}