Thursday, 16 July 2015

Android Alert Dialog

Alert Dialog in Android

Alert Dialog is used for display small message on screen with different options like Yes or No button, Run time enter user data using input box, Icon of message and so on.

Here I provide you sample code for Alert Dialog.

File: res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <Button
        android:id="@+id/buttonAlert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Alert Box" />
 
</LinearLayout>

File: MainActivity.java


package com.android.alertdialogdemo;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
 
public class MainActivity extends Activity 
{ 
 final Context context = this;
 private Button button;
 
 public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
 
     button = (Button) findViewById(R.id.buttonAlert);
 
     // add button listener
     button.setOnClickListener(new OnClickListener() 
            {
  @Override
  public void onClick(View arg0) 
                {
                   AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
    context);
 
   // set title
   alertDialogBuilder.setTitle("Alert Message");
 
   // set dialog message
   alertDialogBuilder.setMessage("Click yes to exit!");
   alertDialogBuilder.setCancelable(false);
   alertDialogBuilder.setPositiveButton
                        ("Yes",new DialogInterface.OnClickListener() 
                        {
                            public void onClick(DialogInterface dialog,int id)
                            {
                               // if this button is clicked, close
         // current activity
         MainActivity.this.finish();
       }
          })
   .setNegativeButton("No",new DialogInterface.OnClickListener() 
                        {
       public void onClick(DialogInterface dialog,int id)
                            {
                                 // if this button is clicked, just close
    // the dialog box and do nothing
    dialog.cancel();
       }
   });
 
   // create alert dialog
   AlertDialog alertDialog = alertDialogBuilder.create();
 
   // show it
   alertDialog.show();
  }
 });
    }
}


Now run your application. When you click on button you can see the alert dialog.


Happy Coding...!!!

No comments:

Post a Comment