前端开发那些事儿

Navigation导航

2020-09-26  本文已影响0人  慕尼黑凌晨四点

Navigation导航

概述

Android Jetpack 组件之一,用来实现不同片段(Fragment)之间的交互导航。且遵循谷歌官方导航既定原则

用途

Navigation 组件旨在用于具有一个主 Activity 和多个 Fragment 目的地的应用。主 Activity 与导航图相关联,且包含一个负责根据需要交换目的地的 NavHostFragment

在具有多个 Activity 目的地的应用中,每个 Activity 均拥有其自己的导航图。

优势

基础用法

  1. 资源文件中新建res/navigation/navigation.xml

  2. activity布局中需要有个一fragment与之(navigation.xml)绑定;

    ...
    //绑定即:后续所有的导航、跳转 都是在这个main_fragment中完成了
    //所以要加`app:defaultNavHost="true"`,拦截系统的返回键,fragment内部响应
    <fragment
        android:id="@+id/main_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/navigation" />
    ...
    
  1. 新建目标fragment(一个或多个),并在navigation.xml中导入,并建立导航(跳转)关系。
image-20200926195332267.png
<?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_graph"
    app:startDestination="@id/HomeFragment">
    <fragment
        //下一步中方法一对应的fragment的ID
        android:id="@+id/HomeFragment"
        android:name="com.cy.navigationtest.HomeFragment"
        android:label="fragment_home"
        tools:layout="@layout/fragment_home" >
        //下一步中方法二对应的action的ID
        <action
            android:id="@+id/next_action"
            app:destination="@id/detailFragment" />
    </fragment>
    <fragment
        android:id="@+id/detailFragment"
        android:name="com.cy.navigationtest.DetailFragment"
        android:label="fragment_detail"
        tools:layout="@layout/fragment_detail" />
</navigation>
  1. fragment中,在对应场景下进行跳转。有两种跳转方式,代码如下:
上一篇下一篇

猜你喜欢

热点阅读