Ad

Android: Write A Class For Using Alert Dialog Every Where

- 1 answer

I am new in android and I have tried to write a class MyAlertDialog for alert dialog to use it every where I need an alert dialog. I have written a method showAlertDialog in the class to do this. I found that the method have to be static. Could anybody tell me why it should be static? Here is my code:

public class MyAlertDialog extends AppCompatActivity {

public static void alertDialogShow(Context context, String message) {

    final Dialog dialog;
    TextView txtAlertMsg;
    TextView txtAlertOk;

    dialog = new Dialog(context);
    dialog.setContentView(R.layout.activity_my_alert_dialog);
    txtAlertOk = (TextView) dialog.findViewById(R.id.txtAalertOk);
    txtAlertMsg = (TextView) dialog.findViewById(R.id.txtAlertMsg);
    txtAlertMsg.setText(message);
    txtAlertOk.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    dialog.show();
}

}

and I have called it like bellow:

MyAlertDialog.alertDialogShow(MainActivity.this,"Here is my message");
Ad

Answer

It is not necessary to be static

You can also do it the non-static way:

public class MyAlertDialog {

private Context context;
private String message;

public MyAlertDialog(Context context,String message){
    this.context = context;
    this.message = message;
}

public void alertDialogShow() {

    final Dialog dialog;
    TextView txtAlertMsg;
    TextView txtAlertOk;

    dialog = new Dialog(context);
    dialog.setContentView(R.layout.activity_my_alert_dialog);
    txtAlertOk = (TextView) dialog.findViewById(R.id.txtAalertOk);
    txtAlertMsg = (TextView) dialog.findViewById(R.id.txtAlertMsg);
    txtAlertMsg.setText(message);
    txtAlertOk.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    dialog.show(); 
}

To call it:

MyAlertDialog myAlertDialog = new MyAlertDialog(MainActivity.this,"Here is my message");

myAlertDialog.alertDialogShow();
Ad
source: stackoverflow.com
Ad