gpt4 book ai didi

android - 在导航中使用 TypeSafe 将多个 Agument 传递给 fragment

转载 作者:行者123 更新时间:2023-12-04 23:54:23 25 4
gpt4 key购买 nike

我知道可以在源 fragment 中使用 Action 传递单个参数

  override fun onClick(v: View) {
val amountTv: EditText = view!!.findViewById(R.id.editTextAmount)
val amount = amountTv.text.toString().toInt()
val action = SpecifyAmountFragmentDirections.confirmationAction(amount)
v.findNavController().navigate(action)

}

并在 android 文档中指定的目标 fragment 中获取它

    val args: ConfirmationFragmentArgs by navArgs()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val tv: TextView = view.findViewById(R.id.textViewAmount)
val amount = args.amount
tv.text = amount.toString()
}

请告诉我有没有办法以 TypeSafe 方式传递多个参数

最佳答案

是的,您可以通过在导航图中为 fragment 定义多个参数,然后将它们传递给代码中的 action 来实现。这是一个例子:

navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/navigation"
app:startDestination="@id/firstFragment">
<fragment
android:id="@+id/firstFragment"
android:name="com.example.app.FirstFragment"
android:label="FirstFragment"
tools:layout="@layout/fragment_first">
<action
android:id="@+id/action_firstFragment_to_secondFragment"
app:destination="@id/secondFragment"
app:enterAnim="@anim/slide_in_right"
app:popExitAnim="@anim/slide_out_left" />
</fragment>
<fragment
android:id="@+id/secondFragment"
android:name="com.example.app.SecondFragment"
android:label="secondFragment"
tools:layout="@layout/fragment_second">
<argument
android:name="firstDataList"
app:argType="com.example.app.domain.FirstData[]" />
<argument
android:name="secondDataList"
app:argType="com.example.app.domain.SecondData[]" />

<argument
android:name="isOkey"
app:argType="boolean" />
<argument
android:name="myString"
app:argType="string" />
</fragment>


</navigation>

然后在您的代码中:

你应该分别传递参数,因为它是 navigation.xml

FirstFragment.kt

findNavController().navigate(
FirstFragmentDirections.actionFirstFragmentToSecondFragment(
firstDataList.toTypedArray(),
secondDataList.toTypedArray(),
isOkey,
myString
)

然后在目的地将其作为 bundle 检索,如下所示:

SecondFragment.kt

val args = arguments?.let {
SecondFragmentArgs.fromBundle(
it
)
}
if (args != null) {
firstDataList = args.firstDataList.toCollection(ArrayList())
secondDataList = args.secondDataList.toCollection(ArrayList())
isOkey = args.isOkey
myString = args.myString

}

要传递复杂对象,您应该使它们parcelable。在我的示例中,我传递了两个复杂模型列表,我将它们像这样分割:

DataModels.kt

@Parcelize
data class FirstData(var id: Int, var color: Int = 0) : Parcelable

@Parcelize
data class SecondData(var name: String, var position: ArrayList<Int>) : Parcelable

关于android - 在导航中使用 TypeSafe 将多个 Agument 传递给 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59540977/

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