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
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?
CodePudding user response:
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()