Display alert dialog box in android example tutorial

Show alert message on android activity using AlertDialog.Builder widget method.

My in this tutorial we will show you how to use custom alert dialog box in android application with different buttons.So here is the complete step by step tutorial for Display alert dialog box in android example tutorial.

android-project-download-code-button

How to Display alert dialog box in android example tutorial.

Code for MainActivity.java file.

 package com.alertdialog_android_examples.com;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

 Button AlertDialogBox;
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 AlertDialogBox = (Button)findViewById(R.id.button1);
 
 AlertDialogBox.setOnClickListener(new View.OnClickListener()
 {
 @Override
 public void onClick(View v) 
 {
 new AlertDialog.Builder(MainActivity.this)
 .setIcon(R.drawable.ic_launcher)
 .setTitle("Alert Dialog Box Title")
 .setMessage("Are you sure( Alert Dialog Message )")
 .setPositiveButton("OK", new DialogInterface.OnClickListener()
 {
 @Override
 public void onClick(DialogInterface dialog, int which) 
 {
 Toast.makeText(MainActivity.this, "You Clicked on OK", Toast.LENGTH_SHORT).show();
 }
 })
 .setNegativeButton("Cancel", new DialogInterface.OnClickListener()
 {
 @Override
 public void onClick(DialogInterface dialog, int which) 
 {
 Toast.makeText(MainActivity.this, "You Clicked on Cancel", Toast.LENGTH_SHORT).show();
 }
 }).show();
 }
 });
 
 }


 }

Code for activity_main.xml layout file.

<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:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.alertdialog_android_examples.com.MainActivity" >

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:text="Click Here To Show Alert Dialog Box" />

</RelativeLayout>

Screenshot:

Display alert dialog box in android example tutorial

alert dialog box-2

Click here to download Display alert dialog box in android example tutorial project.

Leave a Reply

Your email address will not be published. Required fields are marked *