Java how to create alert dialog in android studio

Java how to create alert dialog in android studio

To create an alert dialog in Android Studio, you can use the AlertDialog.Builder class. Here is an example of how you can create an alert dialog in Android:

  1. In your activity's layout file, add a button that will trigger the alert dialog when clicked.
<Button
    android:id="@+id/button_show_alert"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Show Alert" />
‮oS‬urce:www.lautturi.com
  1. In your activity's Java code, define a method that creates and shows the alert dialog when the button is clicked.
public class MainActivity extends AppCompatActivity {
  private Button buttonShowAlert;

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

    buttonShowAlert = findViewById(R.id.button_show_alert);
    buttonShowAlert.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        showAlert();
      }
    });
  }

  private void showAlert() {
    // Create an alert dialog builder
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    // Set the alert dialog title and message
    builder.setTitle("Alert Dialog Title")
        .setMessage("This is the message of the alert dialog.");

    // Add a positive button to the alert dialog
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
        // The user clicked the OK button
      }
    });

    // Create and show the alert dialog
    AlertDialog dialog = builder.create();
    dialog.show();
  }
}

This code creates an AlertDialog.Builder object and sets the title and message of the alert dialog using the setTitle and setMessage methods. It then adds a positive button to the alert dialog using the setPositiveButton method and sets an OnClickListener to handle the button click. Finally, it creates and shows the alert dialog using the create and show methods of the AlertDialog.Builder class.

You can also add negative and neutral buttons to the alert dialog using the setNegativeButton and setNeutralButton methods, respectively. You can also customize the layout of the alert dialog by setting a custom view using the setView method.

Created Time:2017-11-03 22:21:05  Author:lautturi