如何编写可以通过多个片段重复使用的单个函数来导航到单一目的地?

发布于 2025-02-07 07:37:23 字数 327 浏览 2 评论 0原文

假设我有4个片段,并按顺序导航 a - > b - > c - > d使用navcontroller对象。

A是我的主屏幕。

我想写一个称为的单个功能 gotoa()可以从bcd中拨打并从导航到并清除背堆

我该如何处理?

Let's say I have 4 fragments and navigate through them in the order
A -> B -> C -> D using a NavController object.

A is my home screen.

I'd like to write a single function called
goToA() that can be inherited and called from either B, C or D which navigates to A and clears up the back stack

How do I go about that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我只土不豪 2025-02-14 07:37:23

在您的basefragment只需创建函数:

protected fun goToA() {
    findNavController().popBackStack(R.id.<id of fragment A in the nav graph here>, false)
}

现在您可以从bcd调用此函数。

In your BaseFragment just create the function:

protected fun goToA() {
    findNavController().popBackStack(R.id.<id of fragment A in the nav graph here>, false)
}

Now you can call this function from either B, C or D

薄荷港 2025-02-14 07:37:23

您可以为其编写一个扩展功能,该功能在任何类外部的顶层定义,您可以从任何片段中调用:

fun Fragment.goToA() {
    //...
}

You can write an extension function for it, defined at the top level outside any classes, that you can call from any of your Fragments:

fun Fragment.goToA() {
    //...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文