[Android] The dialog, YesNo

In this lesson, you will learn to create and display a dialog box.

For this, you will use the Dialog.

To create a new Dialog, call the method Builder.

AlertDialog.Builder alertDialog = new AlertDialog.Builder(Main.this);

You can specify an icon with the method setIcon(), a title with the method setTitle() and a message with the method setMessage().

alertDialog.setIcon(R.drawable.app);
alertDialog.setTitle("Your title");
alertDialog.setMessage("Your message");

To add a button « positive » (in the meaning of « Yes »), call the method setPositiveButton(). Then add a listener OnClickListener and the method onClick().

alertDialog.setPositiveButton("Yes!", new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int arg1) { }
});

Repeat the operation with a button « negative » (in the meaning of « No »), with the method setNegativeButton().

alertDialog.setNegativeButton("No!", new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int arg1) { }
});

To manage the action of cancel, call the method setOnCancelListener.

alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
  public void onCancel(DialogInterface dialog) { }
});

To display the Dialog, call the method show() :

alertDialog.show();

Layout main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
<Button
    android:id="@+id/btnShow"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Show" />
</LinearLayout>

File Main.java

public class Main extends Activity {
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button btnShow = (Button)findViewById (R.id.btnShow);
    btnShow.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(Main.this);
        alertDialog.setIcon(R.drawable.app);
        alertDialog.setTitle("Your title");
        alertDialog.setMessage("Your message");
        alertDialog.setPositiveButton("Yes!", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int arg1) { }
        });
        alertDialog.setNegativeButton("No!", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int arg1) { }
        });
        alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
          public void onCancel(DialogInterface dialog) { }
        });
        alertDialog.show();
      }
    });
    }
}

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×