Get data back from a fragment dialog - best practices?

A great way to pass this kind of Events is a Callback Interface like descripted in the Android Developers Guide

Your Fragment define a Callback Interface like

public class MyFragment extends Fragment {
    ...
    // Container Activity must implement this interface
    public interface OnArticleSelectedListener {
        public void onArticleSelected(Uri articleUri);
    }
    ...
}

Then you check inside your onAttach Method if the Parent implemented the Callback Interface and save the Instance.

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnArticleSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
    }
}

when your Event inside the Fragment happens you simply call the Callback Handler

mListener.onArticleSelected(...);

Hope that helps, further infos here


As eternalmatt said the given solution does not really answer the question. The way to communicate the dialog with the fragment is calling:

dialog.setTargetFragment(myCallingFragment, requestCode);

The way I do this is by creating the FragmentDialog with an static method where the listener is instanciated an then do the setFragmentTarget() stuff:

public mySuperFragmentDialog extends DialogFragment {
  public interface SuperListener{
     void onSomethingHappened();
  }

  public static mySuperFragmentDialog newInstance(SuperListener listener){
     MySuperFagmentDialog f = new MySuperFragmentDialog();
     f.setTargetFragment((Fragment) listener, /*requestCode*/ 1234);
     return f;
  }
}

To create the dialog from the fragment just do as usual:

Dialog dialog = MySuperFragmentDialog.newInstance(parentFragment);
dialog.show();

Then when you want to comunicate with the fragment which calls the dialog just:

Fragment parentFragment = getTargetFragment();
((SuperListener) parentFragment).onSomethingHappened();

This solution works only when dialog is gonna be created from Fragments and not from Activities, but you can combine both methods ('setFragmentTarget()' and the 'onAttach()' one) plus some Class checks to provide a full solution.

Tags:

Android