toBundle.toPutInt() NavArgs 方法无效

toBundle.toPutInt() method of NavArgs is not working

所以,在Android的Navigation中,当我们想要将参数从FragmentA传递给FragmentB时,我们有两种方法来接收这个参数,通过Bundle,在FragmentB中:

val args: FragmentBArgs 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()
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val tv: TextView = view.findViewById(R.id.textViewAmount)
    val amount = arguments?.getSerializable(KEY_AMOUNT) as Int
    tv.text = amount.toString()
}

两者都有,我通常会得到值。但是,如果我尝试直接在 Bundle 中更改此值,则两者的行为会有所不同。示例:

val args: FragmentBArgs by navArgs()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val tv: TextView = view.findViewById(R.id.textViewAmount)
    var amount = args.amount
    tv.text = amount.toString()
    //Trying to change the value to -1
    args.toBundle().putInt(KEY_AMOUNT, -1)
    amount = args.amount
    //The value of amount remains the same, it is not changed to -1
}

在下面的代码中:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val tv: TextView = view.findViewById(R.id.textViewAmount)
    val amount = arguments?.getSerializable(KEY_AMOUNT) as Int
    tv.text = amount.toString()
    //Trying to change the value to -1
    arguments?.putInt(KEY_AMOUNT, -1)
    amount = args.amount
    //The value of amount is changed and becomes -1
}

它们是两个不同的代码,具有相同的objective。哪个应该有相同的结果,但只有最后一个有预期的结果,使用参数?。

问题是因为使用导航中的 NavArgs 的代码不会将信息更新为 -1,即使我通过代码请求它:args.toBundle().putInt(KEY_AMOUNT, -1)

因为 toBundle() returns 新包考虑以下代码

fun main() {
    val users = listOf("test1", "test2")
    users.toMutableList().add("test3")
    println(users)
    
    // output: [test1, test2]
}

如果我从用户创建一个可变列表,然后在其中添加一个元素,代码会将元素添加到新创建的列表中,因此您的示例没有任何问题。