前提:工程中使用ViewPager,需要导入google提供的jar包(android-support-v4.jar)。
要学习ViewPager的使用,建议直接看官方文档 Creating Swipe Views with Tabs
接下来主要对使用进行下总结,例子是官网上的。
ViewPager可以理解成一个布局(layout)部件,如在xml中加载
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" />
每一个子View作为一个独立的页面,加载在ViewPager上。不过要使子View能作为独立页面插入到ViewPager上,需要实现一个PagerAdapter。
在PagerAdapter类或其子类中设计tab的标题(getPageTitle方法中实现)、tab的数量(在getCount方法中实现)、tab页面的显示内容(即fragment对象,在getItem方法中实现,该方法返回一个fragment对象)。
jar包中已经实现了两种:
用于tab较少、较固定的滑动。效果如图,3个tab:
下面是FragmentPagerAdapter的子类的实现代码
1 public static class AppSectionsPagerAdapter extends FragmentPagerAdapter { 2 3 public AppSectionsPagerAdapter(FragmentManager fm) { 4 super(fm); 5 } 6 7 @Override 8 public Fragment getItem(int i) { 9 switch (i) { 10 case 0: 11 // The first section of the app is the most interesting -- it offers 12 // a launchpad into the other demonstrations in this example application. 13 return new LaunchpadSectionFragment(); 14 15 default: 16 // The other sections of the app are dummy placeholders. 17 Fragment fragment = new DummySectionFragment(); 18 Bundle args = new Bundle(); 19 args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1); 20 fragment.setArguments(args); 21 return fragment; 22 } 23 } 24 25 @Override 26 public int getCount() { 27 return 3; 28 } 29 30 @Override 31 public CharSequence getPageTitle(int position) { 32 return "Section " + (position + 1); 33 } 34 }