导航组件参数默认值

2024-05-21

在导航组件中,将参数从第一个片段发送到第二个片段时,默认值不会从导航图中获取哪个集合。

这是我的代码:

导航图.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/navigation_graph"
    app:startDestination="@id/firstFragment">


    <fragment
        android:id="@+id/firstFragment"
        android:name="com.example.navigationcomponent.FirstFragment"
        android:label="fragment_first"
        tools:layout="@layout/fragment_first" >
        <action
            android:id="@+id/action_firstFragment_to_secondFragment"
            app:destination="@id/secondFragment"
            app:enterAnim="@anim/nav_default_enter_anim" />

        <argument
            android:name="clickFrom"
            app:argType="string"
            android:defaultValue="From First Fragment" />
        <argument
            android:name="clickFragmentPosition"
            app:argType="integer"
            android:defaultValue="1" />

    </fragment>

    <fragment
        android:id="@+id/secondFragment"
        android:name="com.example.navigationcomponent.SecondFragment"
        android:label="fragment_second"
        tools:layout="@layout/fragment_second" />


</navigation>

第一个片段:

class FirstFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val bundle = Bundle()
        bundle.putBoolean("IsFirstFragment", true)
        val navController = Navigation.findNavController(activity!!, R.id.my_nav_host_fragment)

        btnNext.setOnClickListener {
            navController.navigate(R.id.action_firstFragment_to_secondFragment, bundle)
        }
    }
}

第二个片段:

class SecondFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_second, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val isFromFirstFragment = arguments?.getBoolean("IsFirstFragment", false)
        Log.d(TAG, "$isFromFirstFragment")
        Log.d(TAG, "${FirstFragmentArgs.fromBundle(arguments!!).clickFrom} ${FirstFragmentArgs.fromBundle(arguments!!).clickFragmentPosition}")

        val navController = Navigation.findNavController(activity!!, R.id.my_nav_host_fragment)
        btnBack.setOnClickListener {
            navController.navigateUp()
        }

        navController.addOnDestinationChangedListener { controller, destination, arguments ->
            Log.d("TAG", "${destination.label}");
        }
    }

    companion object {
        private const val TAG: String = "SecondFragment"
    }
}

在获取第二个片段中的默认值时,我收到空指针异常

Log.d(TAG, "${FirstFragmentArgs.fromBundle(arguments!!).clickFrom} ${FirstFragmentArgs.fromBundle(arguments!!).clickFragmentPosition}")

我的问题是,如何获取使用设置的参数值navigation_graph.xml?当您重新构建项目时,导航图会自动生成 getter。是否有任何架构可以使用默认值绑定自动生成的设置器?


如果您想从以下位置发送参数FirstFragment to SecondFragment,那么你应该更换你的导航图.xml with:

<?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/navigation_graph"
    app:startDestination="@id/firstFragment">


    <fragment
        android:id="@+id/firstFragment"
        android:name="com.example.navigationcomponent.FirstFragment"
        android:label="fragment_first"
        tools:layout="@layout/fragment_first" >
        <action
            android:id="@+id/action_firstFragment_to_secondFragment"
            app:destination="@id/secondFragment"
            app:enterAnim="@anim/nav_default_enter_anim" />

    </fragment>

    <fragment
        android:id="@+id/secondFragment"
        android:name="com.example.navigationcomponent.SecondFragment"
        android:label="fragment_second"
        tools:layout="@layout/fragment_second">

        <argument
            android:name="clickFrom"
            app:argType="string"
            android:defaultValue="From First Fragment" />

        <argument
            android:name="clickFragmentPosition"
            app:argType="integer"
            android:defaultValue="1" />

        <argument
            android:name="isFirstFragment"
            app:argType="boolean"
            android:defaultValue="false" />

    </fragment>


</navigation>

然后,您可以传递来自您的参数第一个片段像这样:

class FirstFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val navController = Navigation.findNavController(activity!!, R.id.my_nav_host_fragment)

        btnNext.setOnClickListener {
            navController.navigate(
                FirstFragmentDirections.actionFirstFragmentToSecondFragment( // this is an auto-generated class & method
                    // specify your arguments here: For example:
                    isFirstFragment = true,
                    clickFrom = "your argument here",
                    clickFragmentPosition = 1
                    // for default values, you can leave this blank
                )
            )
        }
    }
}

然后检索参数第二个片段

class SecondFragment : Fragment() {

    private val arguments: SecondFragmentArgs by navArgs() // add this line to retrieve arguments from navigation

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_second, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val isFromFirstFragment = arguments.isFirstFragment
        Log.d(TAG, "$isFromFirstFragment")
        Log.d(TAG, "${arguments.clickFrom} ${arguments.clickFragmentPosition}")

        val navController = Navigation.findNavController(activity!!, R.id.my_nav_host_fragment)
        btnBack.setOnClickListener {
            navController.navigateUp()
        }

        navController.addOnDestinationChangedListener { controller, destination, arguments ->
            Log.d("TAG", "${destination.label}");
        }
    }

    companion object {
        private const val TAG: String = "SecondFragment"
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

导航组件参数默认值 的相关文章

随机推荐

  • 使用 VirtualBox 进行远程 Xdebug

    我正在尝试让远程调试工作 PHP 正在虚拟机上运行 我正在尝试从主机上的 NetBeans 进行调试 我已按照说明进行操作here http xdebug org docs remote 在Windows 7防火墙和VirtualBox网络
  • 当您在 .net 项目中添加 dll 的引用时会发生什么

    我在 net 中有一个类库项目 名为 A 构建时将创建一个 dll 即 A dll 我有另一个项目 B 该项目包含 dll A dll 的引用 当我在 B 中添加 A 的引用时到底会发生什么 谁能告诉我在编译时和运行时会发生什么 编译器将
  • ckeditor 字体样式 13 px

    我之前曾问过相关问题 但在尝试了所有发生错误的可能性之后 我发现 在ckeditor中 如果您复制一些文本并粘贴它 它默认粘贴为 p style font size 13px 示例图片 HTML CODE p div p Original
  • 如何将属性保存到 has_many :通过连接表,没有现有记录可供构建

    我有一个表单 可以使用以下命令创建新的子记录和新的父记录accepts nested attributes for 孩子和家长都有一个has many through像这样的关联 class Child lt ActiveRecord Ba
  • Android向后兼容技术

    我现在在开发基于最新 API 15 ICS 的 15 项活动 Android 应用程序方面取得了进展 现在我发现应用程序的主要功能主义者即使支持 android v4 也不向后兼容 例如 1 fragment事务动画 2 将StringSe
  • 使用 xctool 运行单个 KIWI 规范

    有没有人能够成功地将 KW SPEC 变量传递给 xctool 我正在尝试使用以下命令来运行单个 KIWI 规范https github com kiwi bdd Kiwi wiki Kiwi FAQ q how do i run a si
  • 一页上有多个容器

    我最近开始使用 Twitter Bootstrap 并尝试了解它是如何工作的 我正在看流体布局示例 http twitter github com bootstrap examples fluid html源代码 有两个容器 div cla
  • 文件上传后如何隐藏上传按钮?

    我使用 blueimp 和 jquery UI 进行文件上传 我想在上传文件后隐藏此按钮 并在照片被删除时再次显示它 我该怎么做呢 这是我的 HTML
  • 使用 scikit-learn 进行二次采样 + 分类

    我正在使用 Scikit learn 进行二元分类任务 并且我有 0 级 有 200 个观察值 第 1 类 有 50 个观察值 而且因为我有不平衡的数据 我想抽取多数类的随机子样本 其中观察数量与少数类相同 并且希望使用新获得的数据集作为分
  • 如何关闭与数据库的现有连接

    我想关闭与 MS SQL Server 的现有连接 以便可以通过编程方式对该数据库进行恢复 这应该会断开其他所有人的连接 并使您成为唯一的用户 alter database YourDb set single user with rollb
  • 如何在 PHP 中运行 shell 脚本?

    我正在尝试使用 PHP 触发 shell 脚本的运行 本质上 当用户在我们用 PHP 编写的网站上完成一个操作时 我们希望触发一个 shell 脚本 该脚本本身调用一个 Java 文件 提前致谢 See shell exec http ph
  • PhotoChooserTask 抛出未处理的异常

    我已经有了这段代码 我使用它来显示一个按钮 该按钮允许用户从他的库中选择图像并将其用作我的应用程序的背景 所以我创建了一个PhotoChooserTask 将其设置为显示相机并将其绑定到任务完成时必须执行的方法 该按钮将通过显示PhotoC
  • has_many 关系中的 Active Record 对象何时保存?

    我正在使用 Rails 1 2 3 是的 我知道 并且对如何使用感到困惑has many适用于对象持久性 为了举例 我将使用它作为我的声明 class User lt ActiveRecord Base has many assignmen
  • 'numpy.float64'对象没有属性'translate'在Python中将值插入Mysql

    import dataset db dataset connect table db 当我尝试向 Mysql 表中插入一些值时 发生了此错误 我插入表中的示例值 print Buy ticker price date OType OSize
  • 在代码中旋转按钮(或其中的文本)

    我必须通过编码随机旋转按钮 或里面的文本 它是相同的 API级别低于11是否有button setRotate x 好吧 看了一下 答案是 很复杂 您可以使用旧的动画框架旋转按钮 例如像这样 Button button Button fin
  • 运行“npm install”:Node-gyp 错误 - MSBUILD.exe 失败,退出代码:1

    我在跑npm install在 Windows 上安装我的项目中的所有软件包 然后我收到有关 MSBUILD exe 的错误 gyp ERR stack Error C Program Files x86 Microsoft Visual
  • php exec 返回的结果比直接进入命令行要少

    我有一个 exec 命令 它的行为与通过 Penguinet 给 linux 的相同命令不同 res exec cd mnt mydirectory zcat log file gz echo res 当将命令直接放入命令行时 我在日志文件
  • 限制分页页数

    objConnect mysql connect localhost root or die mysql error objDB mysql select db Test strSQL SELECT FROM UserAddedRecord
  • 如何减去两个 gettimeofday 实例?

    我想减去两个 gettimeofday 实例 并以毫秒为单位给出答案 这个想法是 static struct timeval tv gettimeofday tv NULL static struct timeval tv2 gettime
  • 导航组件参数默认值

    在导航组件中 将参数从第一个片段发送到第二个片段时 默认值不会从导航图中获取哪个集合 这是我的代码 导航图 xml