Search code examples
androidkotlinandroid-fragmentsbundle

Pass data between two fragments by bundle kotlin


I have two fragments and want to open second fragment (WordFragment) when pressing button of the first one(SearchFragment) by Bundle. But Fragment shwos default data instead of the passed one.

ClickListener in First Fragment:

 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)
                }
            }
        )

Second Fragment:

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()
    }
}

Solution

  • this is because you create new WordFragment here replace(R.id.searchFragment, WordFragment()) instead of putting the one you added the bundle to it.