官方文档:
https://developer.android.com/reference/android/support/v4/view/ViewPager.html
一、使用步骤
(1)在布局中新建一个ViewPager的控件
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
(2)编写ViewPager特有的Adapter
一般是继承ViewPager的PagerAdapter,主要重写getCount、instantiateItem、destroyItem、isViewFromObject方法
private static final int sMyDrawableIds[] = {
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
};
private class MyPagerAdapter extends PagerAdapter {
private List<View> mListViews;
public MyPagerAdapter(Context context) {
mListViews = new ArrayList<>();
Resources resources = context.getResources();
for (int i = 0; i < 3; ++i) {
ImageView imageView = new ImageView(context);
imageView.setImageDrawable(resources.getDrawable(sMyDrawableIds[i]));
mListViews.add(imageView);
}
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = mListViews.get(position);
container.addView(view);
return view;
}
@Override
public int getCount() {
return mListViews.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
(3)实例化ViewPager并绑定Adapter
private ViewPager mViewPager;
private void initView() {
mViewPager = (ViewPager) findViewById(R.id.clip_tips_step_pager);
mViewPager.setAdapter(new ClipPagerAdapter(mContext));
}
如果设置监听事件,可以采用addOnPageChangeListener(ViewPager.OnPageChangeListener listener)
private class MyPagerChangeListener implements ViewPager.OnPageChangeListener {
@Override
public void onPageSelected(int position) {}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
@Override
public void onPageScrollStateChanged(int state) {}
}
mViewPager.addOnPageChangeListener(new MyPagerChangeListener());
二、一些常用方法
setCurrentItem(int item) : 设置现在选择的页面
三、深入使用
ViewPager 全面剖析及使用详解 http://www.jianshu.com/p/e5abbda4a71c (提高篇)