在 NavController 中避免 Android 导航 IllegalArgumentException [英] Avoiding Android navigation IllegalArgumentException in NavController

查看:31
本文介绍了在 NavController 中避免 Android 导航 IllegalArgumentException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近切换到 Android 导航,但遇到了相当多的情况(在代码的不同部分),我得到:

I recently switched over to Android Navigation, but have encountered a fair amount of situations (in different parts of the code), where I get:

Fatal Exception: java.lang.IllegalArgumentException
navigation destination com.xxx.yyy:id/action_aFragment_to_bFragment is unknown to this NavController

在每种情况下,代码都是简单的调用,例如:

In every case, the code are simple calls like:

findNavController(this, R.id.navigation_host_fragment).navigate(R.id.action_aFragment_to_bFragment)

通常响应按下按钮.

目前还不清楚为什么会抛出这个错误.我目前的怀疑是 onClickListener 在某些设备上以某种方式被调用两次,导致导航被第二次调用(导致它当时处于错误状态).这种怀疑的原因是,这似乎最常发生在导航调用之前可能有一个长时间"运行的操作的情况下.不过,我无法在自己的设备上重新创建它.

It's unclear why this error is getting thrown. My current suspicion is that the onClickListener is somehow getting called twice on some devices, causing the navigate to be called a second time (causing it to be in the wrong state at the time). The reason for this suspicion is that this most often seems to happen in cases where one might have a "long" running operation before the navigate call. I can't recreate this on my own device, though.

关于如何避免这个问题的想法(或者实际上,问题的实际根本原因是什么)?

Ideas on how to avoid this issue (or indeed, what the actual root cause of the issue is)?

我不想使用全局操作;我很担心向后堆栈引入更多意想不到的状态.而且我真的不想在每次进行导航调用时都尝试测试当前状态.

I don't want to use Global Actions; I'm wary of introducing even more unexpected states to the backstack. And I'd really prefer not to have to try and test for the currentstate every time a navigate call is made.

推荐答案

您可以在导航前使用以下代码检查当前目的地是否正确.这将确保调用仅从当前片段发生.可以通过同时单击两个视图(列表中的两个项目)来重现此问题.

You can use the below code before navigating to check whether the current destination is correct or not. This will make sure that the call happens from the current fragment only. This issue can be reproduced by clicking on two views simultaneously(Two items in a list).

if (findNavController().currentDestination?.id == R.id.currentFragment) {
        findNavController().navigate(R.id.action_current_next)
}

这篇关于在 NavController 中避免 Android 导航 IllegalArgumentException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆