Google recommends that we use DialogFragment
instead of a simple Dialog
by using Fragments API
, but it is absurd to use an isolated DialogFragment
for a simple Yes-No confirmation message box. What is the best practice in this case?
Answer
Yes, use DialogFragment
and in onCreateDialog
you can simply use an AlertDialog builder anyway to create a simple AlertDialog
with Yes/No confirmation buttons. Not very much code at all.
With regards handling events in your fragment there would be various ways of doing it but I simply define a message Handler
in my Fragment
, pass it into the DialogFragment
via its constructor and then pass messages back to my fragment's handler as approprirate on the various click events. Again various ways of doing that but the following works for me.
In the dialog hold a message and instantiate it in the constructor:
private Message okMessage;
...
okMessage = handler.obtainMessage(MY_MSG_WHAT, MY_MSG_OK);
Implement the onClickListener
in your dialog and then call the handler as appropriate:
public void onClick(.....
if (which == DialogInterface.BUTTON_POSITIVE) {
final Message toSend = Message.obtain(okMessage);
toSend.sendToTarget();
}
}
Edit
And as Message
is parcelable you can save it out in onSaveInstanceState
and restore it
outState.putParcelable("okMessage", okMessage);
Then in onCreate
if (savedInstanceState != null) {
okMessage = savedInstanceState.getParcelable("okMessage");
}
No comments:
Post a Comment