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

查看:105
本文介绍了在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)

通常是响应按钮的按下.

Usually in response to a button press.

目前尚不清楚为什么会引发此错误.我目前的怀疑是,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天全站免登陆