Sobes.tech
Junior — Middle

How can parameters be passed during Fragment initialization in Android?

sobes.tech AI

Answer from AI

Parameters during Fragment initialization in Android are usually passed through a Bundle object, which is set in the Fragment using the setArguments() method. This is done to ensure that parameters are preserved during the fragment's re-creation by the system.

Example of creating a fragment with parameters:

class MyFragment : Fragment() {
    companion object {
        private const val ARG_PARAM = "param"

        fun newInstance(param: String): MyFragment {
            val fragment = MyFragment()
            val args = Bundle()
            args.putString(ARG_PARAM, param)
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val param = arguments?.getString(ARG_PARAM)
        // Use param as needed
    }
}

Thus, when creating a fragment, the static method newInstance is called, which packages the parameters into a Bundle and sets them in the fragment. This is the standard and recommended way to pass parameters to fragments.