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:
- Create a new Kotlin class for your fragment:
class MyFragment : Fragment() {
// Fragment code goes here
}
- 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.
- Retrieve the arguments in the
onCreate
method of the fragment:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
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.
- 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.
- Finally, add the fragment to your activity using a
FragmentManager
:
supportFragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit()
Replace R.id.container
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.