Junior — Middle
Is it possible to pass arguments when creating an instance of Fragment in Android?
sobes.tech AI
Answer from AI
Yes, passing arguments when creating a Fragment instance in Android is possible and recommended via a Bundle. Usually, a static method newInstance is created that takes necessary parameters, packs them into a Bundle, and sets it in the Fragment via setArguments().
Example:
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 approach ensures that when the fragment is recreated by the system, the passed parameters are restored.