gpt4 book ai didi

android-fragments - 通过 NavGraph 将数据从 Fragment 发送到 Main Activity

转载 作者:行者123 更新时间:2023-12-02 13:33:53 31 4
gpt4 key购买 nike

在我的应用程序中,我使用具有多个片段架构的单个 Activity ,并使用导航库在它们之间导航。在其中一个片段中,我有多个类别,每个类别都与一个 ID 相关联。当点击一个类别时,我会使用下面的代码将用户带到相应的类别解释器屏幕。

    val directions = MainNavGraphDirections.launchFragmentWithThisCategoryId(categoryId!!)
onRoute(AppRoute.Directions(directions))

上面的代码将它们发送到与关联的 categoryId 关联的解释器屏幕。 .一切都很好,直到现在,正确的解释器屏幕基于 categoryId 启动。 .在这个解释器屏幕中,我有一个带有标签 chatbot://fragment/wizardintro 的深层链接。这应该让主要 Activity 知道将用户发送到的特定后续片段。我用下面的代码表示所有可以接收此深层链接的片段。
companion object{
const val DEEP_LINK = "chatbot://fragment/wizardintro"
}

在 MainActivity 中,我有一个方法可以接收所有不同的深度链接意图,并将它们与将使用下面的代码启动相应类别片段的标签进行匹配。
 override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
intent?.data?.toString().also { deepLink ->
when (deepLink) {
IntroductionFragment.DEEP_LINK ->{
val categoryId = intent?.getLongExtra("categoryId", 0L)
val directions = MainNavGraphDirections.actionGlobalGoalWizard(categoryId)
navController.popBackStack()
navController.navigate(directions)
}
}

现在,当我尝试检索此 categoryId 时出现了我的问题在主 Activity 中并将其传递给下一个片段。我什么也没得到,只有默认的 Long 被传递。我认为 MainActivity 中的函数覆盖 fun onNewIntent(intent: Intent?) { } 接收任何意图。需要明确的是,这些意图是从解释器片段发送的,该片段在技术上是加载 json 的片段。在 json 中有一个 "route": {"type": "route", "url": "chatbot:///fragment/wizardintro"

在 MainActivity 中,onNewIntent 函数接收这些意图并使用此行 intent?.data?.toString().also ... 将它们解包。然后在 when 语句中选择一个匹配 chatbot:///fragment/wizardintro 的片段

我说这一切是为了说主要 Activity 实际上并没有获得 categoryId,它只是选择启动必要的片段,而实际上没有任何与 categoryId 相关的内容。

这让我觉得第一次点击的 categoryId 实际上并没有传递给 MainActivity。尽管在我看来,将对象/数据从片段传递到 Activity 似乎并不难。我错过了什么?我可以阅读什么来对自己进行更多的教育?
感谢您的时间和回复!

最佳答案

既然我们已经得出结论 MainActivity没有得到 categoryId , 你只需要传递 categoryIddeep-link .

但是,不需要来自 Fragment 的任何通信。至Activity .
您可以通过 Fragment 之间的通信达到相同的结果。至Fragment , 和 ActivityFragment .

您要做的是更仔细地查看 deep-linksandroid navigation在 AndroidDocs 中,click here .

如您所知,有不同的方法可以解决这个问题,从 arguments 开始。对于每个片段。分配 categoryId作为 argument到 Fragment 将帮助您使用 navigationControllernavigate到新 Fragment ,同时通过 categoryId给它。

现在,我知道您还希望使用 deep-link 启动它。 ; here 上也有很好的解释.根据docs ,您可以放置​​argumentsdeep-links以下列方式...

Placeholders in the form of {placeholder_name} match one or more characters. For example, http://www.example.com/users/{id} matches http://www.example.com/users/4. The Navigation component attempts to parse the placeholder values into appropriate types by matching placeholder names to the defined arguments that are defined for the deep link destination. If no argument with the same name is defined, a default String type is used for the argument value.


navigation是惊人的和有能力的东西,你只需要意识到它实际上可以做的一切。您甚至可以将其绑定(bind)到 BottomNavBar , 代码量极少。

试试看 AndroidDocs关于它,它肯定会在你身上成长。

关于android-fragments - 通过 NavGraph 将数据从 Fragment 发送到 Main Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59828945/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com