Sha*_*ras 8 android kotlin android-architecture-navigation android-safe-args
使用它们后有没有办法清除 navArgs ?我有片段 A 用 navArgs 打开片段 B,然后我导航到片段 C 并且用户按回,所以片段 B 用相同的 navArgs 打开,我不想要那样。
有没有办法在没有 navArgs 的情况下导航回片段 B?
谢谢。
小智 11
胡安霍提出的答案绝对有效。唯一需要注意的是,您不能使用navArgs属性委托来获取它们,因为它是wrapped的Lazy。相反,您只需浏览底层arguments捆绑包即可。
例如,在 FragmentB 中
// don't need to pull in the navArgs anymore
// val args: FragmentBArgs by navArgs()
override fun onResume() {
when (FragmentBArgs.fromBundle(arguments!!).myArg) {
"Something" -> doSomething()
}
// clear it after using it
arguments!!.clear()
}
Run Code Online (Sandbox Code Playgroud)
// 现在当我回到这个片段时它们被清除了
Calling arguments?.clear() is not sufficient. Reason for that is that the navArgs() delegate holds all arguments in a local cached variable. Moreover, this variabel is private:
(taken from NavArgsLazy.kt)
private var cached: Args? = null
override val value: Args
get() {
var args = cached
if (args == null) {
...
args = method.invoke(null, arguments) as Args
cached = args
}
return args
}
Run Code Online (Sandbox Code Playgroud)
I also find this approach pretty stupid. My use-case is a deeplink that navigates the user to a specific menu item of the main screen in my app. Whenever the user comes back to this main screen (no matter wherefrom), the cached arguments are re-used and the user is forced to the deeplinked menu item again.
Since the cached field is private and I don't want to use reflections on this, the only way I see here is to not use navArgs in this case and get the arguments manually the old-school way. By doing so, we can then null them after they were used once:
val navArg = arguments?.get("yourArgument")
if (navArg != null) {
soSomethingOnce(navArg)
arguments?.clear()
}
Run Code Online (Sandbox Code Playgroud)
我认为当你的片段 B 将被销毁时你可以删除参数
getArguments().clear();您可以在 onDestroyView() 中或每当您想要清除片段中的参数时使用该方法。
| 归档时间: |
|
| 查看次数: |
1192 次 |
| 最近记录: |