AlertDialog Example
Let's create a simple program as follows: Whenever the user clicks on a button, an AlertDialog appears on the screen. Then the user chooses 1 out of 3 options and the option selected is shown using Toast.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.example.android.alertdialog.MainActivity">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:text="Learning AlertDialog"
android:textSize="40sp"
/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open AlertDialog"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="100dp"
android:onClick="openDialog"
/>
</RelativeLayout>
MainActivity.java
package com.example.android.alertdialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void openDialog(View v){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Setting AlertDialog Characteristics
builder.setTitle("Learning Dialog");
builder.setMessage("I Love StudyTonight");
//Set Positive Button
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"OK button was pressed",Toast.LENGTH_LONG).show();
}
});
//Set Negative Button
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"Cancel button was pressed",Toast.LENGTH_LONG).show();
}
});
//Set Neutral Button
builder.setNeutralButton("Remind me later", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"Remind me later button was pressed",Toast.LENGTH_LONG).show();
}
});
//Creating AlertDialog
AlertDialog dialog = builder.create();
//Displaying AlertDialog
dialog.show();
}
}
![Alert Dialog Example]()
![Alert Dialog Example]()
![Alert Dialog Example]()