1、XML中注册
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
></android.support.v4.view.ViewPager>
2、在Activity注册
ViewPager viewPager= (ViewPager) findViewById(R.id.viewpager)
3、创建一个保存Fragment的集合,BlankFragment类继承Fragment,在集合里面添加Fragment类对象
List<BlankFragment> fragments = new ArrayList<BlankFragment>();
4、为viewPager设置适配器
viewPager.setAdapter(new MyFragmentAdapter(getSupportFragmentManager()))
//自定义FragmentAdapter适配器
public class MyFragmentAdapter extends FragmentPagerAdapter {
public MyFragmentAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public android.support.v4.app.Fragment getItem(int position) {
return fragments.get(position);
}
}
5、ViewPager视图滑动切换页面滚动监听
viewPager.setOnPageChangeListener(new MyViewPaperListener());
//ViewPager视图滚动监听
public class MyViewPaperListener implements ViewPager.OnPageChangeListener {
@Override//页面滚动的时候
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override//滚动状态被改变的时候
public void onPageSelected(int position) {
}
@Override//页面被选中的时候
public void onPageScrollStateChanged(int state) {
}
}