Android成长日记-使用PagerAdapter实现页面切换
Tip:此方式可以实现页面切换
1. 创建view1.xml,view2.xml,view3.xml,main.xml
在main.xml中创建
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</android.support.v4.view.ViewPager>
2. 创建MainActivity.java
public class MainActivity extends Activity {
private List<View>viewList;[s1]
private ViewPager Pager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewList=new ArrayList<View>();
Pager=(ViewPager) findViewById(R.id.pager);[s2]
//将布局转化为视图
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);[s3]
viewList.add(view1);
viewList.add(view2);
viewList.add(view3);[s4]
//创建PagerAdapter适配器
MyViewPagerAdapter adapter=new MyViewPagerAdapter(viewList);
//ViewPager加载适配器
Pager.setAdapter(adapter);
}
}
3. 创建适配器MyViewPagerAdapter.java
public class MyViewPagerAdapter extends PagerAdapter {
private List<View>viewList;[s5]
public MyViewPagerAdapter(List<View> viewList)
{
this.viewList=viewList;
}[s6]
@Override
public int getCount() {
//返回页卡的数量
return viewList.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
// View是否来自于对象
return arg0==arg1;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {[s7]
// 实例化一个页卡
container.addView(viewList.get(position));
return viewList.get(position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {[s8]
//销毁一个页卡
container.removeView(viewList.get(position));
}[s9]
[s1]创建集合List,泛型为View
[s2]控件实例化
[s3]将布局转换为视图
[s4]添加到集合
[s5]声明List集合
[s6]创建构造方法,用于接收传来的集合
[s7]实例化页卡
[s8]销毁页卡
[s9]新增的两个方法