Home Next Tutorial

How To Display AlertDialog on Button Click in Android


Step 1: Open Android Studio
Step 2: Select File->New->New Project
Step 3: In the Create New Project window type Application Name as "AlertDemo" and click on Next button. In the Target Android Devices select Minimum SDK and click on Next Button. In The Add an Activity to Mobile select blank activity and click on Next Button.Click on Finish button.
Step 4: Design an activity as shown below:

Intent Example
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close Activity"
android:id="@+id/btnClose"

android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

Step 5: Open MainActivity.java file and write following code in the onCreate() method to show Alert Dialog when user click on Push Button.

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button) findViewById(R.id.btnClose);
b1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Confirmation");
// Setting Dialog Message
alertDialog.setMessage("Area You Sure?");
// On pressing Yes button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE,"Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
finish();
}
});
// on pressing No button
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE,"No", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
}

Step 6:Run the application. As you click on Close Activity button it display AlertDialog as shown below:


Download Projects


Download Programs