Search code examples
androidthisandroid-alertdialogcode-reuse

how to reuse android alertdialog


I want to reuse the code for alertDialog and put it in another java file as function call . But "this" cannot be used to replace the "MyActivity.this"? How to pass it as a parameter? Best if the code is generic.

    AlertDialog alertDialog = new AlertDialog.Builder(MyActivity.this).create();
            alertDialog.setTitle("Alert");
            alertDialog.setMessage("Alert message to be shown");
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
            alertDialog.show();

Solution

  • You can use something like this in a separate class, for example I have used AlertUtils.java:

    public class AlertUtils
    {
        public static void showOKDialog(Context context, String title, String message)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(title);
            builder.setMessage(message);
            builder.setPositiveButton(android.R.string.ok, null);
            builder.show();
        }
    }
    

    In this method, the Context you pass through could be your Activity's this, eg: MyActivity.this or a fragment's getContext()

    AlertUtils.showOKDialog(MyActivity.this, "title of dialog", "message to display in dialog");