Sobes.tech
Junior — Middle

How can data be passed to a Fragment without using third-party libraries?

sobes.tech AI

Answer from AI

Passing data to a Fragment without third-party libraries can be done using Bundle arguments. When creating a Fragment instance, create a Bundle, put the data into it, and set it via setArguments(). In the Fragment itself, retrieve the data from getArguments().

Example:

// In an Activity or other place where the Fragment is created
val fragment = MyFragment().apply {
    arguments = Bundle().apply {
        putString("key", "value")
    }
}

// In the Fragment itself
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val data = arguments?.getString("key")
}