Create popup or alert in Android Studio with Java

Tiempo de lectura: < 1 minuto
Creating a popup or alert in Android Studio using the Java programming language is straightforward.

The component we’ll use to create the popup is AlertDialog, which we’ll create with a title, a message, and two buttons: “Accept” and “Cancel.”

Then, we define actions for each button using setPositiveButton and setNegativeButton. In this case, clicking either button will close the popup (dialog.dismiss()).

Below is the complete code:

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showAlert();
    }

    public void showAlert() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("Title")
                .setMessage("This is an alert message for DevCodeLight")
                .setPositiveButton("Accept", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // Action when clicking Accept
                        dialog.dismiss(); // Closes the alert
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // Action when clicking Cancel
                        dialog.dismiss(); // Closes the alert
                    }
                })
                .show();
    }
}

Finally, the result is shown below:

Leave a Comment