在之前的博文《 Fragment中的通信》和《Android中第五大组件详解》中我们介绍了Fragment的使用场景以及不同的实现方式。那如果将他们两结合起来,会不会擦出点火花呢,答案是肯定的。本文将使用viewPager和fragment的结合来完成微信APP。
效果图如上图
(我们可以通过点击下面的导航按钮选择对应的显示界面;我们也可以通过滑动界面(fragment)来实现界面切换,同时下面的导航按钮状态也会发生变化)
那么重点来了,这样的效果要怎么实现呢,大至分为以下的步骤
(1)布局文件中直接部署ViewPager以及下方的导航布局
(2)根据导航的个数来建立对应的fragment布局并建立配套的Fragment类(为方便后期扩展,建议建立与导航个数相同的fragments)
(3)drable下使用selector实现导航组件的形态变化
(4)通过FragmentPagerAdapter(V4包下)实现ViewPager与Fragment的关联
(5)设置下方导航的点击事件以及ViewPager的OnPageChangeListener方法实现对应的状态改变
(6)定义一个activity用来加载闪屏页,使用handler延迟跳转(模拟加载数据的耗时操作)
第一步:layout中的主布局文件activity_main.xml文件
<?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.forget.wechat.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorblack"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:gravity="center_vertical"
android:text="微信"
android:textColor="@color