【Android】Navigation的使用

一、背景

Google推出了FragmentContainerView用来替代FragmentManager进行Fragment管理。

--

二、使用步骤

  1. 在项目根目录build.gradle文件的中,添加如下代码
buildscript {
    ...
    dependencies {
        ...
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.5.0"
    }
}

在新版的AndroidStudio中,Gradle升级到7.2+后,可以将如下代码添加到根目录的build.gradle文件的顶顶部

buildscript {
    dependencies {
        classpath 'androidx.navigation:navigation-safe-args-gradle-plugin:2.5.0'
    }
}
  1. 在module/build.gradle文件中,添加apply plugin: "androidx.navigation.safeargs.kotlin",否则不能生成XXXDirections类;

  2. 在用到FragmentContainerView的Module中,引用navigation库,代码如下:

    implementation 'androidx.navigation:navigation-fragment-ktx:2.4.1'
    implementation 'androidx.navigation:navigation-ui-ktx:2.4.1'
  1. 在Module的res/navigation目录下创建对应的导航图表文件,如nav_main_graph.xml

  2. 创建Activity及对应布局文件,并在布局文件中使用FragmentContainerView组件

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragment_container_view"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/main_nav_graph" />
  1. 创建对应的Fragment及布局,如:LoginFragment、HomeFragment,并在导航图表文件nav_main_graph.xml中添加对应Fragment
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/nav_main_graph"
    app:startDestination="@id/loginFragment">

    <fragment
        android:id="@+id/loginFragment"
        android:name="com.bytb.login.LoginFragment"
        android:label="LoginFragment">
        <action
            android:id="@+id/action_goto_home"
            app:destination="@id/homeFragment" />
    </fragment>
    <fragment
        android:id="@+id/homeFragment"
        android:name="com.bytb.login.HomeFragment"
        android:label="HomeFragment" />
</navigation>

注:这里可以通过拖拽指针来指定各View之间的关系

  1. 视图添加、拖拽演示

  2. 导航到指定视图,如从LoginFragment转入到HomeFragment

findNavController().navigate(LoginFragmentDirections.actionGotoHome())
  1. 返回到上一级视图
findNavController().popBackStack()
  1. 返回到指定的页面
    当我们在业务中进行如下页面导航顺序时FragmentA->DialogFragmentA->DialogFragmentB->DialogFragmentC,当前是在DialogFragmentC页面,在此页面调用dismiss方法,会发现只返回到了DialogFragmentB,而正常情况下,我们是希望返回到弹出弹窗的FragmentA页面,那么我们可以使用NavController.kt类提供的如下方法达到目的,源码如下:
    /**
     * Attempts to pop the controller's back stack back to a specific destination.
     *
     * @param destinationId The topmost destination to retain
     * @param inclusive Whether the given destination should also be popped.
     *
     * @return true if the stack was popped at least once and the user has been navigated to
     * another destination, false otherwise
     */
    @MainThread
    // 参数一:回退到指定的destinationId
    // 参数二:表示是否把指定的destinationId也清退出回退栈
    public open fun popBackStack(@IdRes destinationId: Int, inclusive: Boolean): Boolean {
        return popBackStack(destinationId, inclusive, false)
    }

我们可以在DialogFragmentC中调用以下方法,直接返回到FragmentA页面并把之前的DialogFragmentA->DialogFragmentB->DialogFragmentC都清退出回退栈:

findNavController().popBackStack(R.id.FragmentA_destinationId, false)

如果我们想要返回到FragmentA页面的上一级,那么只需要修改参数二为true即可:

findNavController().popBackStack(R.id.FragmentA_destinationId, true)

11.回传参数给上一层的Fragment
当我们从FragmentA导航到FragmentB进行操作时,如果我们在结束当前FragmentB时想要返回指定的参数给FragmentA,那么可以通过SavedStateHandle+LiveData进行对应的参数值传递:
FragmentA.kt

findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<String>("PARAMETER_KEY")?.observe(viewLifecycleOwner) {

}

FragmentB.kt

val navController = findNavController()
navController.previousBackStackEntry?.savedStateHandle?.set("PARAMETER_KEY", "testValue")
navController.popBackStack()

Android 使用 navigation 时传递参数的两种方式
SavedStateHandle组件解析
Android Navigation 如何回传参数


三、Navigation结合BottomNavigationView的使用

Activity布局文件中,添加NavigationBottomNavigationView

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".home.MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_container"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@+id/bottom_navigation_view"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:navGraph="@navigation/nav_main" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation_view"
        android:layout_width="0dp"
        android:layout_height="@dimen/common_measure_56dp"
        android:background="@color/white"
        app:itemIconTint="@drawable/selector_bottom_tab"
        app:itemTextAppearanceActive="@style/bottom_tab_title_active"
        app:itemTextAppearanceInactive="@style/bottom_tab_title_inactive"
        app:itemTextColor="@drawable/selector_bottom_tab"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_nav_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>

导航对应的graph文件nav_main.xml内容如下:

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/nav_main"
    app:startDestination="@id/navigation_home">
    <fragment
        android:id="@+id/navigation_home"
        android:name="com.xxx.HomeFragment"
        android:label="HomeFragment"
        tools:layout="@layout/fragment_home"/>
    <fragment
        android:id="@+id/navigation_mine"
        android:name="com.xxx.MineFragment"
        android:label="MineFragment"
        tools:layout="@layout/fragment_mine"/>
</navigation>

BottomNavigationView对应的菜单文件bottom_nav_menu.xml内容如下:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/navigation_home"
        android:icon="@drawable/ic_bn_home_n"
        android:title="@string/tab_home" />

    <item
        android:id="@+id/navigation_mine"
        android:icon="@drawable/ic_bn_mine_n"
        android:title="@string/tab_mine" />

</menu>

注意:graph文件、menu文件中的id要保持一致,即<fragment><item>标签的id必须一致。

ActivityBottomNavigationViewNavigation关联即可:

val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_container) as NavHostFragment
mViewBinding.bottomNavigationView.setupWithNavController(navHostFragment.navController)

四、使用过程中的异常情况

1、Navigation action/destination com.xxx:id/action_x cannot be found from the current destination

// 调用navigate跳转之前先判断
// https://blog.csdn.net/qq_26658969/article/details/125642527
if (navController.currentDestination?.id == R.id.Afragment) {
    navController.navigate(R.id.action_Afragment_to_Bfragment)
}

2、在http请求回调中使用Navigation导航报异常错误:Method addObserver must be called on the main thread

刚开始以为是http请求出了问题,各种调试。。。后来发现。。。
又是一个android BUG NavController在调用时Method addObserver must be called on the main thread

参考自

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容