Skip to main content

How to use fragment arguments in Kotlin Android

How to use fragment arguments in Kotlin Android.

Here's a step-by-step tutorial on how to use fragment arguments in Kotlin Android:

  1. Create a new Kotlin class for your fragment:
class MyFragment : Fragment() {
// Fragment code goes here
  1. Declare the arguments you want to pass to the fragment as properties in the companion object of the fragment class:
companion object {
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

fun newInstance(param1: String, param2: String): MyFragment {
val fragment = MyFragment()
val args = Bundle()
args.putString(ARG_PARAM1, param1)
args.putString(ARG_PARAM2, param2)
fragment.arguments = args
return fragment

In this example, we are passing two string parameters (param1 and param2) to the fragment.

  1. Retrieve the arguments in the onCreate method of the fragment:
override fun onCreate(savedInstanceState: Bundle?) {
arguments?.let {
val param1 = it.getString(ARG_PARAM1)
val param2 = it.getString(ARG_PARAM2)
// Use the arguments as needed

Here, we are using the arguments property of the fragment to retrieve the passed arguments. Then, we can access the values using the keys defined in the companion object.

  1. To create an instance of the fragment and pass the arguments, use the newInstance method:
val fragment = MyFragment.newInstance("Hello", "World")

Here, we are creating a new instance of the fragment and passing the arguments "Hello" and "World" to it.

  1. Finally, add the fragment to your activity using a FragmentManager:
.replace(, fragment)

Replace with the ID of the container where you want to add the fragment.

That's it! You have successfully used fragment arguments in Kotlin Android. You can now pass arguments to your fragment and retrieve them within the fragment's onCreate method.