Navigation 组件使用入门

本文是关于Android Navigation组件的使用入门。首先介绍了如何添加依赖,接着详细讲解如何创建导航图,包括导航图的XML结构和页面跳转信息。然后解释了navigation资源文件中的字段含义,特别是fragment的设置。最后提到了一个具体的homeFragment示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Navigation 组件使用入门https://developer.android.google.cn/guide/navigation/navigation-getting-started

添加依赖

dependencies {
  def nav_version = "2.5.2"

  implementation "androidx.navigation:navigation-fragment:$nav_version"

}

创建导航图

导航图,是一个xml文件,里面记录的所有的页面信息,和页面之间的跳转信息

如需向项目添加导航图,请执行以下操作:

  1. 在“Project”窗口中,右键点击 res 目录,然后依次选择 New > Android Resource File。此时系统会显示 New Resource File 对话框。
  2. 在 File name 字段中输入名称,例如“nav_graph”。
  3. 从 Resource type 下拉列表中选择 Navigation,然后点击 OK

当您添加首个导航图时,Android Studio 会在 res 目录内创建一个 navigation 资源目录。该目录包含您的导航图资源文件(例如 nav_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"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/nav_graph_photo"
    app:startDestination="@id/photo">

    <fragment
        android:id="@+id/photo"
        android:name="com.example.gallery3.ui.photo.PhotoFragment"
        tools:layout="@layout/fragment_photo"/>


</navigation>

navigation字段说明:

id:导航图的唯一id

startDestination:该导航图的根fragment

fragment:标识这个是fragment

字段说明:

        id:标识唯一id

        name:fragment类的全限定名

        layout:可以预览样式

一个homeFragment

public class PhotoHomeFragment extends BaseFragment {
    public PhotoHomeFragment() {
        super(R.layout.fragment_photo_home);
    }
}

homeFragment的xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.fragment.app.FragmentContainerView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:id="@+id/nav_host_fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    app:defaultNavHost="true"
    app:navGraph="@navigation/nav_graph_photo">

</androidx.fragment.app.FragmentContainerView>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值