##Getting results from DialogFragments to another Fragment.
When setting up the DialogFragment make a call to Fragment.setTargetFragment()
Then from DialogFragment you can access the main fragment with
Fragment.getTargetFragment()
Use interfaces to provide the required actions to the calling Fragment.
##Example code.
###AddFriendDialogFragment - Calls back to calling fragment.
public class AddFriendDialogFragment extends SherlockDialogFragment {
private OnAddFriendListener callback;
public interface OnAddFriendListener {
public void onAddFriendSubmit(String friendEmail);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
callback = (OnAddFriendListener) getTargetFragment();
} catch (ClassCaseException e) {
throw new ClassCastException("Calling Fragment must implement OnAddFriendListener");
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getSherlockActivity());
builder.setTitle(R.string.dialog_add_friend)
.setMessage(R.string.dialog_add_friend_text)
.setView(editText)
.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Grab the text from the input
final String friendEmail = editText.getText().toString();
callback.onAddFriendSubmit(friendEmail);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
AddFriendDialog.this.getDialog().cancel();
}
});
return builder.create();
}
###Main fragment which displays the dialog and receives the callbacks from the dialog.
public class FriendsFragment extends SherlockListFragment implements OnAddFriendListener {
...
private void showDialog() {
FragmentManager fm = getSherlockActivity().getSupportFragmentManager();
AddFriendDialogFragment addFriendDialog = new AddFriendDialogFragment();
addFriendDialog.setTargetFragment(this, 0);
addFriendDialog.show(fm, "add_friend_dialog");
}
@Override
public void onAddFriendSubmit(String friendEmail) {
// Do stuff
}
}
Man ... you're a life saver !!
Was stuck with this a couple of hours .. Y_Y