Android中Fragment和ViewPager那点事儿(仿微信APP)

本文介绍如何在Android中结合ViewPager和Fragment,模仿微信应用的界面切换效果。通过点击导航按钮或滑动屏幕,实现场景间的平滑过渡,并同步更新导航组件的状态。主要步骤包括设置主布局、创建fragment布局、定义导航组件的形态变化、建立FragmentPagerAdapter以及处理点击事件和页面监听。
摘要由CSDN通过智能技术生成

在之前的博文《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)通过FragmentPagerAdapterV4包下)实现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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值