I understand mostly everything in this code, except when newIstance() is being used. Could anyone please explain. Much appreciated.
public class DateDialogFragment extends DialogFragment {
public static String TAG = "DateDialogFragment";
static Context sContext;
static Calendar sDate;
static DateDialogFragmentListener sListener;
public static DateDialogFragment newInstance(Context context, int titleResource, Calendar date){
DateDialogFragment dialog = new DateDialogFragment();
sContext = context;
sDate = date;
Bundle args = new Bundle();
args.putInt("title", titleResource);
dialog.setArguments(args);
return dialog;
}
}
I made an edit, I guess its working differently when its static. I assume thats why I am confused. How is the method changed when its static? I don’t really see why not do it in the constructor?
When using fragments (any class that extends
Fragment) you frequently need to pass some data. That’s achieved by using thesetArgumentsmethod which receives aBundle. Since doing so requires a lot of code (create the bundle, take into account key names, etc.), it is common to pass the data to a static method (usually callednewInstance). The idea of that method is to create the arguments bundle and pass it to theFragment; then it returns the fragment and you can put it where ever you want.Another advantage of using fragments that way is that when you are inserting a fragment directly in an XML layout, there must be an empty constructor (or nothing at all). If you create a fragment with a constructor (to pass its necessary data) you could get some errors regarding the missing empty constructor.