TLDR: I'm wondering if there is any harm in using Fragment
callbacks to pass in arguments instead of using a Fragment#newInstance
method and setting up a bundle.
As described here, the "proper" way of setting up a Fragment
is by creating a static method that calls the empty constructor and sets up bundles. This is needed because Android sometimes needs to recreate your Fragment
and can only use the empty constructor to do so.
For complex datatypes this means implementing Parcelable
which can be a lot of work. I'm wondering if there is any harm in using Fragment
callbacks to pass in these arguments by having the parent Activity
implement these callbacks and send in parameters.
Example:
Fragment Class:
class MyFragment extends Fragment {
ComplexDatatype = mComplexDatatype;
OnFragmentInteractionListener = mListener;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onActivityCreate(){
// Initialized member variables now
mComplexDatatype = mListener.onGetComplexDatatype();
}
public interface OnFragmentInteractionListener {
public ComplexDataType onGetComplexDatatype();
}
}
Parent Activity Class:
class MyActivity extends Activity
implements MyFragment.OnInteractionListener {
@Override
public ComplexDatatype onGetComplexDatatype(){
return new ComplexDatatype(...);
}
}