How to put a button that performs an AlertDialog.Builder action?

0

I have this method where you display a message.

public void mensagenExebir(String titulo, String texto){

         AlertDialog.Builder mensagem = new AlertDialog.Builder(Activity.this);
         mensagem.setTitle(titulo);
         mensagem.setMessage(texto);
         mensagem.setNeutralButton("OK", null);
         mensagem.show();
     }  

Can you put another button to execute a command?

    
asked by anonymous 22.01.2016 / 00:44

2 answers

3

Just add using the setPositiveButton() :

public void mensagenExebir(String titulo, String texto){

         AlertDialog.Builder mensagem = new AlertDialog.Builder(Activity.this);
         mensagem.setTitle(titulo);
         mensagem.setMessage(texto);
         mensagem.setNeutralButton("Cancelar", null);
         mensagem.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
               // ação a ser executada ao clicar no botão
           }
       });
         mensagem.show();
     }
  

It is recommended that for all string of interface (as the   buttons, and labels), you create a resource in the strings.xml file.   In this way, it facilitates the maintenance and internationalization of   your application.

Reference:

link

    
22.01.2016 / 00:59
4

As far as I know using AlertDialog.Builder only to put up to 3 buttons ... button "POSITIVE" (setPositiveButton), neutral button (setNeutralButton), and "NEGATIVE" (setNegativeButton), but if you want more things like a CheckBox or a progress bar use the object Dialog

Example of a custom dialog:

public void showDialog() {
    final Dialog dialog = new Dialog(MainActivity.this);

    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(androidialog.graphics.Color.TRANSPARENT));
    dialog.setContentView(R.layout.layout_dialog); // seu layout
    dialog.setCancelable(false);

    Button cancelar = (Button) dialog.findViewById(R.idialog.cancelar);
    Button ok = (Button) dialog.findViewById(R.idialog.ok);

    cancelar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        dialog.dismiss(); // fecha o dialog
        }
    });
    ok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             dialog.dismiss(); // fecha o dialog
        }
    });
    dialog.show();
    }
    
27.01.2016 / 00:08