ViewPager类直接继承了ViewGroup类,所有它是一个容器类,可以在其中添加其他的View类。
ViewPager类需要一个PagerAdapter适配器类给它提供数据。
ViewPager经常和Fragment一起使用,并且提供了专门的FragmentPagerAdapter和FragmentStatePagerAdapter类供Fragment中的ViewPager使用。
ViewPager的功能就是可以使视图滑动,就像Lanucher左右滑动那样。分三个步骤来使用它:
1.在住布局文件里加入
2.加载要显示的页卡
3.在Activity里实例化ViewPager组件,并设置它的Adapter(就是PagerAdapter,方法与ListView一样的),在这里一般需要重写PagerAdapter。
当你实现一个PagerAdapter,你必须至少覆盖以下方法:
1. instantiateItem(ViewGroup, int) //返回视图对象
2. destroyItem(ViewGroup, int, Object) //销毁视图对象
3. getCount() //视图个数
4. isViewFromObject(View, Object) //一般传入arg0==arg1.用来判断两个视图是否是等价的
XML配置
<android.support.v4.view.ViewPager
android:
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</android.support.v4.view.ViewPager>
在res/drawable下建立选择器
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:id="@+id/activity_main" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent"> 5 6 <LinearLayout 7 android:layout_width="match_parent" 8 android:layout_height="wrap_content" 9 android:orientation="vertical"> 10 <!-- <android.support.design.widget.TabLayout 11 android: 12 android:layout_width="match_parent" 13 android:layout_height="wrap_content" />--> 14 15 16 <android.support.v4.view.ViewPager 17 android:id="@+id/viewPager" 18 android:layout_width="match_parent" 19 android:layout_height="match_parent"> 20 <!--系统默认PagerTabStrip和PagerTabStrip指示器的唯一区别是 21 PagerTabStrip可以点,PagerTabStrip不能点--> 22 <android.support.v4.view.PagerTabStrip 23 android:id="@+id/pts" 24 android:layout_width="match_parent" 25 android:layout_height="wrap_content"> 26 27 </android.support.v4.view.PagerTabStrip> 28 29 </android.support.v4.view.ViewPager> 30 </LinearLayout> 31 <LinearLayout 32 android:id="@+id/ll_points" 33 android:layout_width="wrap_content" 34 android:layout_height="wrap_content" 35 android:orientation="horizontal" 36 android:layout_alignParentBottom="true" 37 android:layout_marginBottom="50dp" 38 android:layout_centerHorizontal="true"> 39 40 </LinearLayout> 41 </RelativeLayout>