Android-Jetpack笔记-Navigation之Fragment支持复用

上篇文章Android-Jetpack笔记-Navigation之Fragment使用提到,每次切换目的地,fragment是反复销毁重建的,按照谷歌推荐的1个APP只需1个activity的思路开发,这样是没问题的,但是这里的fragment是作为首页的3个常驻页面,我们是希望能够保存起来的,毕竟,销毁重建需要重新请求网络数据,重新初始化view,严重影响用户体验,那么接下来继续上篇文章的分析,支持Fragment的复用。

Jetpack笔记代码

本文源码基于SDK 29,IDE是 Android Studio Arctic Fox | 2020.3.1 Patch 2

解决

给上篇文章的项目加些日志,从面板页切到通知页,再从通知页切回面板页,查看日志,

可见面板页发生了销毁重建,接着创建一个ReuseFragmentNavigatorKotlin继承FragmentNavigator并重写navigate方法,直接把父类的实现copy过来,第1步,在调用fragment初始化的地方,改成复用:

//ReuseFragmentNavigatorKotlin.kt
override fun navigate(
    destination: Destination,
    args: Bundle?,
    navOptions: NavOptions?,
    navigatorExtras: Navigator.Extras?,
): NavDestination?{
	//......
    //fix 1: 把类名作为tag,寻找已存在的Fragment
    //(如果想只针对个别fragment进行保活复用,可以在tag上做些标记比如加个前缀,这里不再展开)
	var frag = mFragmentManager.findFragmentByTag(className)
	frag = frag ?: instantiateFragment(mContext, mFragmentManager, className, args)
	//......
}

第2步,将ft.replace换成show和hide

//ReuseFragmentNavigatorKotlin.kt
override fun navigate(
    destination: Destination,
    args: Bundle?,
    navOptions: NavOptions?,
    navigatorExtras: Navigator.Extras?,
): NavDestination?{
	//......
	val fragments = mFragmentManager.fragments
	for (fragment in fragments) {
	    ft.hide(fragment!!)
	}
	if (!frag.isAdded) {
	    ft.add(mContainerId, frag, className)
	}
    //ft.replace(mContainerId, frag);
    //fix 2: replace换成show和hide	
	ft.show(frag)
	ft.setPrimaryNavigationFragment(frag)
    //......
}

第3步,反射获取父类的mBackStack

//ReuseFragmentNavigatorKotlin.kt
override fun navigate(
    destination: Destination,
    args: Bundle?,
    navOptions: NavOptions?,
    navigatorExtras: Navigator.Extras?,
): NavDestination?{
	//......
    //fix 3: mBackStack是私有的,而且没有暴露出来,需要反射获取
	var mBackStack: ArrayDeque<Int>? = null
	try {
	    val aClass = FragmentNavigator::class.java
	    val mBackStackField = aClass.getDeclaredField("mBackStack")
	    mBackStackField.isAccessible = true
	    //mBackStack = mBackStackField.get(this) as ArrayDeque  //也行
	    mBackStack = mBackStackField[this] as ArrayDeque<Int>
	} catch (e: Exception) {
	    e.printStackTrace()
	    return null
	}
    //......
}

第4步,把父类的私有方法generateBackStackName也copy过来,

//ReuseFragmentNavigatorKotlin.kt
//fix 4: 从父类那边copy过来即可
private fun generateBackStackName(backStackIndex: Int, destId: Int): String {
    return "$backStackIndex-$destId"
}

第5步,给ReuseFragmentNavigatorKotlin加上注解给他取个名字,原因放后面说,

//fix 5: 需要指定1个名字,源码里自带的名字有navigation、activity、fragment、dialog
@Navigator.Name("reuseFragment")
class ReuseFragmentNavigatorKotlin(
    private val mContext: Context,
    private val mFragmentManager: FragmentManager,
    private val mContainerId: Int,
) : FragmentNavigator(mContext, mFragmentManager, mContainerId){
}

至此ReuseFragmentNavigatorKotlin就写好了

完整代码

@Navigator.Name("reuseFragment")
class ReuseFragmentNavigatorKotlin(
    private val mContext: Context,
    private val mFragmentManager: FragmentManager,
    private val mContainerId: Int,
) : FragmentNavigator(mContext, mFragmentManager, mContainerId) {
    override fun navigate(
        destination: Destination,
        args: Bundle?,
        navOptions: NavOptions?,
        navigatorExtras: Navigator.Extras?,
    ): NavDestination? {
        if (mFragmentManager.isStateSaved) {
            Log.i(TAG, "Ignoring navigate() call: FragmentManager has already"
                    + " saved its state")
            return null
        }
        var className = destination.className
        if (className[0] == '.') {
            className = mContext.packageName + className
        }
        var frag = mFragmentManager.findFragmentByTag(className)
        frag = frag ?: instantiateFragment(mContext, mFragmentManager, className, args)

        frag.arguments = args
        val ft = mFragmentManager.beginTransaction()
        var enterAnim = navOptions?.enterAnim ?: -1
        var exitAnim = navOptions?.exitAnim ?: -1
        var popEnterAnim = navOptions?.popEnterAnim ?: -1
        var popExitAnim = navOptions?.popExitAnim ?: -1
        if (enterAnim != -1 || exitAnim != -1 || popEnterAnim != -1 || popExitAnim != -1) {
            enterAnim = if (enterAnim != -1) enterAnim else 0
            exitAnim = if (exitAnim != -1) exitAnim else 0
            popEnterAnim = if (popEnterAnim != -1) popEnterAnim else 0
            popExitAnim = if (popExitAnim != -1) popExitAnim else 0
            ft.setCustomAnimations(enterAnim, exitAnim, popEnterAnim, popExitAnim)
        }
        val fragments = mFragmentManager.fragments
        for (fragment in fragments) {
            ft.hide(fragment!!)
        }
        if (!frag.isAdded) {
            ft.add(mContainerId, frag, className)
        }
        //ft.replace(mContainerId, frag);
        ft.show(frag)
        ft.setPrimaryNavigationFragment(frag)

        var mBackStack: ArrayDeque<Int>? = null
        try {
            val aClass = FragmentNavigator::class.java
            val mBackStackField = aClass.getDeclaredField("mBackStack")
            mBackStackField.isAccessible = true
            //mBackStack = mBackStackField.get(this) as ArrayDeque  //也行
            mBackStack = mBackStackField[this] as ArrayDeque<Int>
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }

        @IdRes val destId = destination.id
        val initialNavigation = mBackStack.isEmpty()
        // TODO Build first class singleTop behavior for fragments
        val isSingleTopReplacement = (navOptions != null && !initialNavigation
                && navOptions.shouldLaunchSingleTop()
                && mBackStack.peekLast() == destId)
        val isAdded: Boolean
        isAdded = if (initialNavigation) {
            true
        } else if (isSingleTopReplacement) {
            if (mBackStack.size > 1) {
                mFragmentManager.popBackStack(
                    generateBackStackName(mBackStack.size, mBackStack.peekLast()),
                    FragmentManager.POP_BACK_STACK_INCLUSIVE)
                ft.addToBackStack(generateBackStackName(mBackStack.size, destId))
            }
            false
        } else {
            ft.addToBackStack(generateBackStackName(mBackStack.size + 1, destId))
            true
        }
        if (navigatorExtras is Extras) {
            for ((key, value) in navigatorExtras.sharedElements) {
                ft.addSharedElement(key!!, value!!)
            }
        }
        ft.setReorderingAllowed(true)
        ft.commit()
        // The commit succeeded, update our view of the world
        return if (isAdded) {
            mBackStack.add(destId)
            destination
        } else {
            null
        }
    }

    private fun generateBackStackName(backStackIndex: Int, destId: Int): String {
        return "$backStackIndex-$destId"
    }

    companion object {
        private const val TAG = "ReuseFragmentNavigator"
    }
}

接下来要如何把它使用进去呢?

先在布局文件中去掉app:navGraph="@navigation/publicwelfare_navigation",然后来到activity,编写如下代码,

//PublicWelfareActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    //获取页面容器NavHostFragment
    val fragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as Fragment
    //获取导航控制器
    NavHostFragment.findNavController(fragment)
        .apply {
        	//自定义Fragment导航器
            val fragmentNavigator =
                ReuseFragmentNavigatorKotlin(this@PublicWelfareActivity,
                    fragment.childFragmentManager,
                    fragment.id)
            //添加自定义的Fragment导航器 到 导航器提供者 中        
            navigatorProvider.addNavigator(fragmentNavigator)
            //手动创建导航图
            graph = initNavGraph(navigatorProvider, fragmentNavigator)
        }
}

//手动创建导航图,把目的地添加进来
private fun initNavGraph(
     provider: NavigatorProvider,
     fragmentNavigator: FragmentNavigator,
 ): NavGraph {
     return NavGraph(NavGraphNavigator(provider)).apply {
         //用自定义的导航器来创建目的地
         val prosFragDest: FragmentNavigator.Destination =
             fragmentNavigator.createDestination().apply {
             	 //这些是之前去掉的导航文件 publicwelfare_navigation 中的配置信息,对照配置上去就行
                 id = R.id.projectsFragment
                 className = ProjectsFragment::class.qualifiedName!!
                 label = "公益项目列表"
             }
         //添加目的地到导航图中
         addDestination(prosFragDest)

         val proDetailDest: FragmentNavigator.Destination =
             fragmentNavigator.createDestination().apply {
                 id = R.id.donateWollarFragment
                 className = DonateWollarFragment::class.qualifiedName!!
                 label = "公益项目详情"
             }
         addDestination(proDetailDest)

         //创建并添加更多目的地到导航图...
         //...

         //设置最初目的地
         startDestination = R.id.projectsFragment
     }
 }

具体流程都写在代码注释里了,至此就实现了对fragment的复用。

前边提到的自定义导航器需要指定名字@Navigator.Name("reuseFragment"),是因为不同类型的目的地(页面)需要使用不同的导航器,在NavigatorProvider里有个map存储了多个导航器,

//NavigatorProvider.java
private final HashMap<String, Navigator<? extends NavDestination>> mNavigators =
            new HashMap<>();

// "navigation" NavGraphNavigator
// "activity" ActivityNavigator
// "fragment" FragmentNavigator
// "dialog" DialogFragmentNavigator
// "reuseFragment" ReuseFragmentNavigatorKotlin 这个就是我们自定义的导航器

然后,使用自定义导航器ReuseFragmentNavigatorKotlincreateDestination创建目的地,这样就把导航器和目的地绑定在一起了。可以看出,Navigation的思想是,把各种类型的页面都抽象成目的地Destination,进行统一跳转,不同的导航器则封装了不同类型页面跳转的实现,由NavController统一调度,而许许多多的目的地则编织成了一个导航图NavGraph

你可能感兴趣的:(Android,Jecpack,Navigation,Fragment)