Sobes.tech
Junior — Middle

Is it possible to initialize a Fragment with parameters through a constructor in Android?

sobes.tech AI

Answer from AI

Initializing a Fragment with parameters through a constructor is not recommended and can lead to issues, as Android may recreate fragments by calling the no-argument constructor.

The correct way is to use a static method newInstance, which creates the fragment and passes parameters via a Bundle using setArguments:

public class MyFragment extends Fragment {
    private static final String ARG_PARAM = "param";

    public static MyFragment newInstance(String param) {
        MyFragment fragment = new MyFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM, param);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            String param = getArguments().getString(ARG_PARAM);
            // use param
        }
    }
}

This ensures the correct restoration of the fragment's state by the Android system.

Is it possible to initialize a Fragment with… - sobes.tech