ViewPager android 提供的基础V4包,android studio 导入gradle
compile 'com.android.support:support-v4:25.0.0'
1.布局使用
<android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" />
2.代码类似listview使用
a.定义重写PagerAdapter
主要实现以下几个函数
instantiateItem(ViewGroup, int)
destroyItem(ViewGroup, int, Object)
getCount()
isViewFromObject(View, Object)
public class MyViewPagerAdapter extends PagerAdapter{ private List<View> mListViews; public MyViewPagerAdapter(List<View> mListViews) { this.mListViews = mListViews;//构造方法,参数是我们的页卡,这样比较方便。 } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(mListViews.get(position));//删除页卡 } @Override public Object instantiateItem(ViewGroup container, int position) { //这个方法用来实例化页卡 container.addView(mListViews.get(position), 0);//添加页卡 return mListViews.get(position); } @Override public int getCount() { return mListViews.size();//返回页卡的数量 } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0==arg1;//官方提示这样写 } }
b.定义ViewPager 及使用
setAdapter.
3.效果