通过 bundle kotlin 在两个片段之间传递数据

Pass data between two fragments by bundle kotlin

我有两个片段,我想在按 Bundle 的第一个片段 (SearchFragment) 的按钮时打开第二个片段 (WordFragment)。但是片段显示默认数据而不是传递的数据。

第一个片段中的 ClickListener:

 searchDefAdapter = SearchDefAdapter(
            object : SearchDefAdapter.OnItemClickListener {
                override fun onItemClick(position: Int) {
                    val bundle = Bundle()
                    val arr = arrayOf("word", "слово", "I give you my word")
                    bundle.putStringArray(INFO_BUNDLE_ID, arr)
                    val wordFragment = WordFragment()
                    wordFragment.arguments = bundle
                    parentFragmentManager.beginTransaction().apply {
                        replace(R.id.searchFragment, WordFragment())
                        commit()
                    }
                }
            },
            object : SearchDefAdapter.OnItemClickListener {
                override fun onItemClick(position: Int) {
                    //viewModel.saveWord(position)
                }
            }
        )

第二个片段:

class WordFragment : Fragment() {
    private var _binding: FragmentWordBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentWordBinding.inflate(inflater, container, false)
        val view = binding.root

        arguments?.let {
            val translation = it.getStringArray(INFO_BUNDLE_ID)
            if (translation != null){
                binding.wordTitleTv.text = translation[0]
                binding.translationTv.text = translation[1]
                binding.exampleTv.text = translation[2]
            }
        }

        return view
    }

    override fun onDestroyView() {
        _binding = null
        super.onDestroyView()
    }
}

这是因为您在此处创建了新的 WordFragment replace(R.id.searchFragment, WordFragment()),而不是将您添加的捆绑包放入其中。