gpt4 book ai didi

android - 导航到 fragment 时传递安全参数

转载 作者:太空宇宙 更新时间:2023-11-03 12:44:08 24 4
gpt4 key购买 nike

使用navigation 时很容易传递safe-args通过一个 Action (使用方向类)。但是在直接使用导航 fragment 的情况下,如何传递safe-args呢?

navController?.navigate(R.id.detailFragment)

导航图:

<fragment
android:id="@+id/detailFragment"
android:name="com.example.ui.main.detail.DetailFragment"
android:label=" "
tools:layout="@layout/detail_fragment" >
<argument
android:name="templateCode"
app:argType="string" />
<action
android:id="@+id/action_start_guide"
app:destination="@id/fillInfoFragment" />
</fragment>

最佳答案

使用类型安全的方式是个好主意,因为它会给您带来编译时安全和一些便利。

此库将构建参数的类 MyDestinationArgs。您可以使用它来构建 Bundle 并以这种方式将结果传递到目的地:

val args = DetailFragmentArgs.Builder("template_code").build().toBundle()
navController?.navigate(R.id.confirmationAction, args)

在接收方,您也可以使用参数类检索数据:

val templateCode = SecondFragmentArgs.fromBundle(arguments).templateCode

如果由于某些原因我们不能使用safeargs库,

我们也可以在 Bundle 中传递数据。假设你添加了

const val ARG_TEMPLATE_CODE = "templateCode"

DetailFragmentcompanion object 中的常量(Java 中的static final 字段)

现在你可以这样传递数据了:

val args = Bundle()
args.putString(DetailFragment.ARG_TEMPLATE_CODE, "some_code")
navController?.navigate(R.id.confirmationAction, args)

接收 fragment 可以从参数中获取数据:

arguments?.getString(ARG_TEMPLATE_CODE)

或者,如果目标目的地是 Activity,您可以从 intent extras 获取数据(ARG_TEMPLATE_CODE constant now from destination activity):

intent?.extras?.getString(ARG_TEMPLATE_CODE)


在文档中阅读更多信息 herehere .

关于android - 导航到 fragment 时传递安全参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52622699/

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