0

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(...);
    }
}
Community
  • 1
  • 1
bcorso
  • 45,608
  • 10
  • 63
  • 75

1 Answers1

1

This is an interesting idea. However, it would mean that any activity that uses the fragment would have to implement the interface, which in turn complicates the design. Whereas you could have the ComplexDataType implements parcelable and another activity or fragment could easily pass it around. Or you could pass what's inside ComplexDataType by itself.

CChi
  • 3,054
  • 1
  • 20
  • 15