Sobes.tech
Junior — Middle

Is it possible to be sure that changing settings will invoke the user constructor of the fragment?

sobes.tech AI

Answer from AI

No, it cannot be guaranteed that changing the settings will invoke the fragment's user-defined constructor.

In Android, the system may recreate fragments using the parameterless (default) constructor, especially when restoring state after a configuration change (e.g., screen rotation).

Therefore, it is recommended to:

  • Use the default parameterless constructor.
  • Pass parameters via a Bundle using the setArguments() method.
  • Retrieve parameters in the onCreate() or onCreateView() method from getArguments().

This ensures the fragment's state is correctly restored by the system.

Example:

class MyFragment : Fragment() {
    companion object {
        fun newInstance(param: String): MyFragment {
            val fragment = MyFragment()
            val args = Bundle()
            args.putString("param_key", param)
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val param = arguments?.getString("param_key")
        // Use param
    }
}
Is it possible to be sure that changing settings will… - sobes.tech