Thursday, March 20, 2014

Android Tip: Displaying Dialogs

In Android, you usually use a dialog to solicit a reply from the user. The most commonly used dialog is a yes/no dialog.
  
You can create a dialog using the AlertDialog class. The following shows a quick way to display a yes/no dialog:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        new AlertDialog.Builder(this)
        .setTitle("Delete Item")
        .setMessage("Are you sure you want to delete this?")
        .setPositiveButton(android.R.string.yes,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,
                                    int which) {
                Toast.makeText(getBaseContext(),
                    "YES", Toast.LENGTH_LONG).show();
            }
         })
        .setNegativeButton(android.R.string.no,
            new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,
                                int which) {
                Toast.makeText(getBaseContext(),
                    "NO", Toast.LENGTH_LONG).show();
            }
         })
        .setIcon(R.drawable.ic_launcher)
        .show();       
    }

The above code displays the dialog as shown below:
  

No comments: