Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading