Junior — Middle
Is it possible to implement the use of arguments in the constructor for Fragment in Android?
sobes.tech AI
Answer from AI
It is not recommended to use constructors with arguments for Fragments in Android, as the system may recreate the fragment at any time by calling the no-argument constructor.
The correct way to pass data to a Fragment is to use the setArguments(Bundle) method and retrieve the data through getArguments() inside the fragment.
Example of creating a fragment with arguments:
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
}
}
Thus, data is stored in a Bundle and correctly restored by the system when recreating the fragment.