One day I realised that my Android project utilizes AlertDialogs here and there in very ineffective way. The heavily duplicated portion of code looked like this (actually, copied and pasted from some documentation):
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure you want to close application?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.dismiss();
System.runFinalizersOnExit(true);
System.exit(0);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.dismiss();
}
});
builder.create().show();
Apparently, this code fragment should be transformed into a function accepting 2 parameters: a question to ask, and an action to perform.
After several iterations of code optimizations (each one of which seemed as the last and most minimal one), I came to the following class:
public abstract class DialogCallback implements DialogInterface.OnClickListener,Runnable
{
DialogCallback(Context c, String q)
{
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setMessage(q)
.setPositiveButton("Yes", this)
.setNegativeButton("No", this);
builder.create().show();
}
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
if(which == DialogInterface.BUTTON_POSITIVE) run();
}
}
with the following usage:
new DialogCallback(context, "are you sure?")
{
public void run()
{
// some action
}
};
Is there a way of further optimization? What other methods for effective dialog callbacks can be used?
1 Answer 1
for a confirmation dialog use setCancelable(true) to make the user able to cancel the dialog using the back button. This is the native way and you don't have to implement anything.
Note: in Android you are not supposed to close the application. The operating system will close it when it feels like to do so.
-
\$\begingroup\$ Thanks for your response, yet I don't think we should discuss application design (as opposed to programming techniques) in the context of this question. This area is very controversial itself. \$\endgroup\$Stan– Stan2012年05月13日 20:20:52 +00:00Commented May 13, 2012 at 20:20