I\'m migrating my dialogs, currently using Activity.showDialog(DIALOG_ID);
, to use the DialogFragment
system as discussed in the android reference.
Yeah, this is a common trap I'm falling in all the time myself. First of all let me say that your solution of calling DialogTest.udateListener()
in onResume()
seems to be fully appropriate to me.
An alternative way would be to use a ResultReceiver
which can be serialized as a Parcelable
:
public class DialogTest extends DialogFragment {
public static DialogTest newInstance(ResultReceiver receiver, int titleId, int messageId) {
DialogTest frag = new DialogTest();
Bundle args = new Bundle();
args.putParcelable("receiver", receiver);
args.putInt("titleId", titleId);
args.putInt("messageId", messageId);
frag.setArguments(args);
return frag;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int titleId = getArguments().getInt("titleId");
int messageId = getArguments().getInt("messageId");
ResultReceiver receiver = getArguments().getParcelable("receiver");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// dialog title
builder.setTitle(titleId);
// dialog message
builder.setMessage(messageId);
// dialog negative button
builder.setNegativeButton("No", new OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
receiver.sendResult(Activity.RESULT_CANCEL, null);
}});
// dialog positive button
builder.setPositiveButton("Yes", new OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
receiver.sendResult(Activity.RESULT_OK, null);
}});
// create the Dialog object and return it
return builder.create();
}}
Then you can handle everything in the Receiver like this:
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (getActivity() != null){
// Handle result
}
}
Check out ResultReceiver doesn't survire to screen rotation for more details. So in the end you probably still need to rewire the ResultReceiver
with your Activity
. The only difference is that you decouple the Activity
from the DialogFragment
.