How to place a button that performs a Alertdialog.Builder action?

Asked

Viewed 1,861 times

0

I have this method where it displays 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();
     }  

You can put another button to execute a command?

  • How so put another button? Explain better what you want to do with this code.

  • @Diegofelipe already has a button that is mensagem.setNeutralButton("OK", null); would like to create one more that will execute a command.

2 answers

4

As far as I know using AlertDialog.Builder You can 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();
    }

3


Just add using the method 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 interface (such as the legend of buttons and buttons), you create a resource in the archive strings.xml. In this way, it facilitates the maintenance and also the internationalization of your app.

Reference:

http://developer.android.com/intl/pt-br/guide/topics/ui/dialogs.html

Browser other questions tagged

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