Android-Alert Dialog
Dialogue is a little window that displays messages asking the user to choose or provide more information. Gives options like Ok and cancel.
Now write the code under the activity_main.xml, and this is the screen that is visible before opening the alert.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello here is a Alert Dialog."
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Under the MainActivity.java create an alert that is created programmatically.
package com.example.alertdialog;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// Set the message show for the Alert time
builder.setMessage("Do you want to exit ?");
// Set Alert Title
builder.setTitle("Alert !");
builder.setCancelable(false);
builder.setPositiveButton("Yes", (DialogInterface.OnClickListener) (dialog, which) -> {
// When the user click yes button then app will close
finish();
});
builder.setNegativeButton("No", (DialogInterface.OnClickListener) (dialog, which) -> {
// If user click no then dialog box is canceled.
dialog.cancel();
});
AlertDialog alertDialog = builder.create();
// Show the Alert Dialog box
alertDialog.show();
}
}
