在之前的博文《Android中使用ViewPager实现屏幕页面切换和引导页效果实现》和《Android中Fragment的两种创建方式》以及《Android中Fragment与Activity之间的交互(两种实现方式)》中我们介绍了ViewPager以及Fragment各自的使用场景以及不同的实现方式。
那如果将他们两结合起来,会不会擦出点火花呢,答案是肯定的。之前在介绍ViewPager时,我们实现了多个ImageView的切换,并配合更新导航原点的状态。那我们现在就将之前的imageview替换为fragment,将导航原点替换为更加生动的布局,比如我们经常使用的微信(取消了ActionBar):
(1)我们可以通过点击下面的导航按钮选择对应的显示界面(fragment),如下图:
(2)我们也可以通过滑动界面(fragment)来实现界面切换,同时下面的导航按钮状态也会发生变化,如下图:
那么重点来了,这样的效果要怎么实现呢,大至分为以下的步骤
(1)布局文件中直接部署ViewPager以及下方的导航布局
(2)根据导航的个数来建立对应的fragment布局并建立配套的Fragment类(为方便后期扩展,建议建立与导航个数相同的fragments)
(3)drable下使用selector实现导航组件的形态变化
(4)通过FragmentPagerAdapter(V4包下)实现ViewPager与Fragment的关联
(5)设置下方导航的点击事件以及ViewPager的OnPageChangeListener方法实现对应的状态改变
第一步:layout中的主布局文件activity_main.xml文件
取消了actionBar,采用LinearLayout嵌套来实现主布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.viewpagerfragment.MainActivity">
<LinearLayout
android:background="@color/colorblack"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center_vertical"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:text="潘侯爷微信"
android:textSize="20sp"
android:textColor="@color/colorWhite"/>
<ImageView
android:src="@mipmap/jy_drltsz_btn_addperson"
android:adjustViewBounds="true"
android:maxHeight="23dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/colornormal"/>
<LinearLayout
android:orientation="horizontal"
android:padding="5dp"
android