Android Alert Dialog

Android Alert Dialog Definition

Android alert dialog is a tiny windows that prompts an individual to produce a decision usually yes or no or enter into more information. An android alert dialog will not fill the display and is generally used for modal occasions that want users for taking an action before they can proceed

android alert dialog

Some right times in the application, if you wished to ask an individual about going for a decision between yes or no in response of any particular action considered by an individual, by left over in the same activity and without changing the display screen, you may use Alert Dialog.

To make an android alert dialog, you will need to make an subject of AlertDialogBuilder which an internal course of Android Alert Dialog. Its syntax is listed below

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

 

You now have to create the yes or no button using the thing of the AlertDialogBuilder category. It is a simple syntax is

alertDialogBuilder.setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener)
alertDialogBuilder.setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener

 

You may use other functions provided by the builder class to customize the android alert dialog. These following below

Sr. No:     Method type

  1. setIcon(Drawable icon)
  2. setCancelable(boolean cancel able)
  3. setMessage(CharSequence message)
  4. setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener)
  5. setOnCancelListener(DialogInterface.OnCancelListener onCancelListener)
  6. setTitle(CharSequence title)

After environment and creating the dialogue builder , you will generate an android alert dialog by contacting the create() approach to the builder category. Its syntax is

AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

 

This will generate the android alert dialog and can show it on the display screen.

Android Dialog fragment

Before enter an example we ought to need to find out dialog fragment.Dialog fragment is a fragment which can show fragment in dialog box

public class DialogFragment extends DialogFragment {
   @Override
   public Dialog onCreateDialog(Bundle savedInstanceState) {
      // Use the Builder class for convenient dialog construction
      AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
      builder.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
            toast.makeText(this,"enter a text here",Toast.LENTH_SHORT).show();
         }
      })
      .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
            finish();
         });
         // Create the AlertDialog object and return it
         return builder.create();
      }
   }
}

 

Android List dialog

It offers used showing set of items in an android dialog box.For suppose, consumer need to choose a set of items if not need to click a item from multiple set of items.As of this situation we may use list dialog.

public Dialog onCreateDialog(Bundle savedInstanceState) {
   AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
   builder.setTitle(Pick a Color)
   
   .setItems(R.array.colors_array, new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
         // The 'which' argument contains the index position
         // of the selected item
      }
   });
   return builder.create();
}

 

Android Single-choice list dialog

It includes used to include sole choice list to android Dialog box.We are able to check or uncheck according to user choice

public Dialog onCreateDialog(Bundle savedInstanceState) {
   mSelectedItems = new ArrayList();
   AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
   
   builder.setTitle("This is list choice dialog box");
   .setMultiChoiceItems(R.array.toppings, null,new DialogInterface.OnMultiChoiceClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which, boolean isChecked) {
         
         if (isChecked) {
            // If the user checked the item, add it to the selected items
            mSelectedItems.add(which);
         }
         
         else if (mSelectedItems.contains(which)) {
            // Else, if the item is already in the array, remove it 
            mSelectedItems.remove(Integer.valueOf(which));
         }
      }
   })
   
   // Set the action buttons
   .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int id) {
         // User clicked OK, so save the mSelectedItems results somewhere
         // or return them to the component that opened the dialog
         ...
      }
   })
   
   .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int id) {
         ...
      }
   });
   return builder.create();
}

 

Android Alert Dialog Example

This android alert dialog example demonstrates the utilization of android Alert Dialog

To test out this example , you will need to perform this with an emulator or a genuine device.

Steps     Description

  1. You use Android studio to produce an App and name it as My Application under a offer bundle com.example.sappal.myapplication; While creating this job, be sure to Concentrate on SDK and Compile With at the latest version of Android os SDK to utilize higher degrees /level of APIs.
  2. Modify src/MainActivity.java data file to include android alert dialog code to start the dialog.
  3. Modify design XML res/structure/activity_main.xml add any GUI element if required.
  4. No need to improve default string constants. Google android studio manages default strings at ideals/string.xml
  5. Run the application form and choose a operating google android device and set up the application onto it and confirm the results.

This is actually the revised code of src/MainActivity.java


Do You Have Any Question About This Tutorial? Ask Question Now On Andro Development & Get Answer Instantly. No Signup/Login Needed


package com.example.sappal.myapplication;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   
   public void open(View view){
      AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
      alertDialogBuilder.setMessage("Are you sure");
      
      alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface arg0, int arg1) {
            Toast.makeText(MainActivity.this,"You clicked yes button",Toast.LENGTH_LONG).show();
         }
      });
      
      alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialog, int which) {
            finish();
         }
      });
      
      AlertDialog alertDialog = alertDialogBuilder.create();
      alertDialog.show();
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
   
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}

 

Following is the modified code of res/layout/activity_main.xml

<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">
   
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Alert Dialog"
      android:id="@+id/textView"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Andro Develoment"
      android:id="@+id/textView2"
      android:textColor="#ff3eff0f"
      android:textSize="35dp"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/logo"
      android:layout_below="@+id/textView2"
      android:layout_alignRight="@+id/textView2"
      android:layout_alignEnd="@+id/textView2"
      android:layout_alignLeft="@+id/textView"
      android:layout_alignStart="@+id/textView" />
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Alert dialog"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_alignRight="@+id/textView2"
      android:layout_alignEnd="@+id/textView2"
      android:layout_marginTop="42dp"
      android:onClick="open"
      android:layout_alignLeft="@+id/imageView"
      android:layout_alignStart="@+id/imageView" />
      
</RelativeLayout>

 

Following is the code of Strings.xml

<resources>
    <string name="app_name">My Application</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
</resources>

 

Following is the default code of AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.alertdialog"
   android:versionCode="1"
   android:versionName="1.0" >

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.sappal.myapplication.MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>

 

Let’s make an effort to run the application. I suppose you have linked your actual Android os Mobile device with your personal computer. To perform the software from Android studio room, available one of your project’s activity data and click Run Eclipse Run Icon android alert dialog from the toolbar. Prior to starting the application, Android studio will show pursuing window to choose a choice where you want to perform your Android request.

android-alert-dailog

Choose your a choice and select it. For suppose, if you have clicked on yes button, result would the following then

android-alert-dailog

if you select no button it’ll call finish() and it’ll close the application.

 


Do You Have Any Question About This Tutorial? Ask Question Now On Andro Development & Get Answer Instantly. No Signup/Login Needed