AlertDialog with single button example : Android

To create an Android AlertDialog with just a single button we can make use of any one method that is provide i.e. one of setPositiveButton(), setNegativeButton() or setNeutralButton() .

AlertDialog with Single Button
AlertDialog with Single Button

Lets create an example where in we have some Information that has to be displayed to the user in a form of a Dialog, it should have a Dismiss button, when clicked the message must hide.

AlertDialog Snippet
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

        builder.setTitle("Information!");

        builder.setMessage("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\n" +
                "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\n" +
                "quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\n" +
                "consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\n" +
                "cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\n" +
                "proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");

        builder.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this,"Get Started!",Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }
        });

        AlertDialog diag = builder.create();

        //Display the message!
        diag.show();

This is not an AI-generated article but is demonstrated by a human on an M1 Mac running macOS Sonoma 14.0.

Please support independent contributors like Code2care by donating a coffee.

Buy me a coffee!

Buy Code2care a Coffee!

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!