在项目中,我们常常需要实现界面滑动切换的效果。例如,微信界面的左右滑动切换效果。那这种效果是怎么实现的?今天我就带大家简单了解ViewPager,并通过实例来实现该效果。
一. ViewPager 官方API
首先我们来看一下ViewPager官方给出的解释,如图:
具体意思如下:
Layout 管理器允许用户可以在页面上,左右滑动来翻动页面。你可以考虑实现PagerAdapter接口来显示该效果。
ViewPager很多时候会结合Fragment一块使用,这种方法使得管理每个页面的生命周期变得很方便。其中,有一些adapter的具体实现,可以适合于这种ViewPager结合Fragment使用的情况。这些adapter包括:FragmentPagerAdapter,和 FragmentStatePagerAdapter。
而本文就是通过ViewPager结合Fragment利用FragmentpagerAdapter适配器来实现左右滑动的效果。
二.效果如下:
三.代码实现:
1.xml布局文件
1>主布局activity_main.xml
- <span style="font-family:Microsoft YaHei;font-size:18px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <include layout="@layout/activity_main_top_tab" />
- <android.support.v4.view.ViewPager
- android:id="@+id/id_page_vp"
- android:layout_width="match_parent"
- android:layout_height="0dp"
- android:layout_weight="1" >
- </android.support.v4.view.ViewPager>
- </LinearLayout></span>
2>顶部导航activity_main_top_tab.xml
- <span style="font-family:Microsoft YaHei;font-size:18px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical" >
- <LinearLayout
- android:id="@+id/id_switch_tab_ll"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal"
- android:baselineAligned="false"
- >
- <LinearLayout
- android:id="@+id/id_tab_chat_ll"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:background="@drawable/guide_round_selector"
- android:gravity="center"
- android:orientation="horizontal"
- android:padding="10dip" >
- <TextView
- android:id="@+id/id_chat_tv"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:text="聊天"
- android:textColor="#0000FF"
- android:textSize="15dip" />
- </LinearLayout>