How to retain listener on custom dialog opened from fragment?
I ran through all of the options on the discussed links and none of the solutions ended up working for me. I also tried a number of additional options after further googling like get/setTargetFragment, and FragmentManager.put/getFragment. These didn't work for me either. Then I took another look at:
http://developer.android.com/training/basics/fragments/communicating.html
Where they specifically say "Two Fragments should never communicate directly". I think this is one of the cases where that's really proven true.
I ended up implementing the suggested callback mechanism provided there and ended up with this:
In DialogFragment:
public interface OnEditStepDialogListener {
public void onEditStepDialogPositive(int pos, String description);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnEditStepDialogListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnEditStepDialogListener");
}
}
In hosting Activity:
public class MyActivity extends SherlockFragmentActivity implements EditStepFragmentDialog.OnEditStepDialogListener {
...
@Override
public void onEditStepDialogPositive(int pos, String desc) {
FragmentManager fm = getSupportFragmentManager();
RecipeDetailEditFragment ef = (RecipeDetailEditFragment)fm.findFragmentByTag(RecipeDetailEditFragment.TAG);
ef.applyStepEdit(pos, desc);
}
In Fragment that fires off the FragmentDialog:
public static final String TAG = "tag1";
public void applyStepEdit(int pos, String description) {
...
}
This works perfectly, if opened then orientation change and edit is completed, it actually triggers the ultimate function I need run in the calling Fragment instead of either crashing or not doing anything (null listener).