AlertDialog from another class

2

My problem is this, I have an Activity that calls methods from a common Java class to perform operations.

Now I've come up with the need for one of these methods to be AlertDialog , I've researched in several places and can not find a solution, can anyone help?

    
asked by anonymous 24.08.2016 / 16:51

2 answers

3

Create a method in your separate class with the following parameters:

public static void showAlert(Context context, String title, String message){

        AlertDialog alertDialog = new AlertDialog.Builder(context).create(); 
        alertDialog.setTitle(title);
        alertDialog.setMessage(message);
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
        alertDialog.show();

}

Then to call it, do the following:

SuaClasseOndeEstaoMetodo.showAlert(this, "Erro", "A imagem não pode ser carregada");
    
24.08.2016 / 16:57
2

Create a class:

public class Message {

    public static void Alert(Context context, String Mensagem) {

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

        //ADICIONANDO UM TITULO A NOSSA MENSAGEM DE ALERTA
        alertDialog.setTitle(R.string.app_name); //ou alertDialog.setTitle("Nome do app");

        //MENSAGEM A SER EXIBIDA
        alertDialog.setMessage(Mensagem);

        //CRIA UM BOTÃO COM O TEXTO OK SEM AÇÃO
        alertDialog.setPositiveButton("OK", null);

        //MOSTRA A MENSAGEM NA TELA
        alertDialog.show();

    }
}

And to "call" Alert use:

Message.Alert(this, this.getString(R.string.save)); 
//ou Message.Alert(this, "Mensagem Desejada");

Note: If you use strings , in values \ strings.xml add:

<string name="save">Salvo com Sucesso!</string>
<string name="app_name">Nome do App</string>
    
24.08.2016 / 18:16