Alertdialog from another class

Asked

Viewed 533 times

2

My problem is this, I have a Activity calling methods of a common Java class for performing operations.

Now I have arisen the need for one of these methods to be a AlertDialog, I have already researched in several places and I can not find solution, someone can help?

  • 2

    Can you explain this problem better? Who knows any code? I don’t understand what your problem is.

2 answers

4


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();

}

Here’s what you do:

SuaClasseOndeEstaoMetodo.showAlert(this, "Erro", "A imagem não pode ser carregada");

3

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" the Alert use:

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

Note: If to use strings, in values strings.xml add:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.