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

Change TextView text from Bundle Fragment

I have a fragment manager that I created, on my main activity as below

supportFragmentManager.beginTransaction().replace(R.id.fragment1, ProduceFragment.newInstance("Title")).commit()

and new Instance function that saves the title on bundle

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

from different file (Produce.kt) as below

fun newInstance(title: String): ProduceFragment {
            val frag = ProduceFragment()
            val bundle = Bundle()
            bundle.putString(titleKey, title)
            Log.d("XXX", "title $title")
            return frag }

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val text =savedInstanceState?.getBundle(titleKey)
        binding.title.text = text.toString()

I see the title on Log.d but I kept getting null. How do I use the bundle to change my title.text?

>Solution :

In your code, you are only creating the bundle but not using it anywhere. You need to attach that bundle to the fragment.

fun newInstance(title: String): ProduceFragment {
    val frag = ProduceFragment()
    val bundle = Bundle()
    bundle.putString(titleKey, title)
    frag.arguments = bundle
    return frag
}

And to retrieve this title value, you can use:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val text = arguments?.getString(titleKey)
    binding.title.text = text.toString()
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