Wednesday, April 8, 2015

How to use AlertDialog in Android

1. Android AlertDialog Example

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:padding="16dp"
    tools:context=".MainActivity"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:textColor="#C71585"
        android:textSize="30dp"
        android:text="Click The Button To Hide This Text...."
        />
    <Button
        android:id="@+id/btn"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Hide TextView"
        android:onClick="onButtonClicked"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
MainActivity.java (Partial code)

public void onButtonClicked(View v){
 //Get widgets reference from XML layout
 final TextView tv = (TextView) findViewById(R.id.tv);

 //Initialize a new AlertDialog Builder
 AlertDialog.Builder adb = new AlertDialog.Builder(this);

 //Set the dialog title
 adb.setTitle("Title of Alert Dialog");

 //Define Alert Dialog Message
 adb.setMessage("Are you want to hide the Text?");

 //Specify this dialog is not cancelable
 adb.setCancelable(false);

 //Set the Yes/Positive and No/Negative Button text
 String yesButtonText = "Yes";
 String noButtonText = "No";

 //Define the positive button text and action on alert dialog
 adb.setPositiveButton(yesButtonText, new DialogInterface.OnClickListener() {
  @Override
  public void onClick(DialogInterface dialog, int which){
   //Do something when user press ok button from alert dialog

   //.......Hide the TextView...........
   //View.GONE remove the space taken by widget
   //View.INVISIBLE hide the widget but keep the space
   tv.setVisibility(View.INVISIBLE);
  }
 });

 //Define the negative button text and action on alert dialog
 adb.setNegativeButton(noButtonText, new DialogInterface.OnClickListener(){
    @Override
  public void onClick(DialogInterface dialog, int which){
     //Do something when user press no button from alert dialog
    }
 });

 //Display the Alert Dialog on app interface
 adb.show();
}
Additional imported classes

import android.content.DialogInterface;
import android.widget.TextView;
import android.view.View;
import android.app.AlertDialog;


2. Three Buttons Alert Dialog

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:padding="16dp"
    tools:context=".MainActivity"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:textColor="#006400"
        android:textSize="25dp"
        android:text="Click the button to make text to italic..."
        />
    <Button
        android:id="@+id/btn"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Apply Italic"
        android:onClick="onButtonClicked"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
MainActivity.java (Partial code)

public void onButtonClicked(View v){
 //Get widgets reference from XML layout
 final TextView tv = (TextView) findViewById(R.id.tv);

 //Initialize a new AlertDialog Builder
 AlertDialog.Builder adb = new AlertDialog.Builder(this);

 //Define Alert Dialog Message
 adb.setMessage("Are you want to make the text italic?");

 //Define the positive button text and action on alert dialog
 adb.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
  @Override
  public void onClick(DialogInterface dialog, int which){
   //Do something when user press ok button from alert dialog
   //Set the TextView text to italic
   tv.setTypeface(tv.getTypeface(), Typeface.ITALIC);
  }
 });

 //Define the negative button text and action on alert dialog
 adb.setNegativeButton("No", new DialogInterface.OnClickListener(){
    @Override
  public void onClick(DialogInterface dialog, int which){
     //Do something when user press no button from alert dialog
    }
 });

 //Define the Alert Dialog's Cancel/Neutral button text and action
 adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener(){
  @Override
  public void onClick(DialogInterface dialog, int which){
   //Do something when user press cancel button on alert dialog
  }
 });

 //Display the Alert Dialog on app interface
 adb.show();
}
Additional imported classes

import android.content.DialogInterface;
import android.widget.TextView;
import android.view.View;
import android.app.AlertDialog;
import android.graphics.Typeface;

3. Traditional Single Choice List On AlertDialog

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:padding="16dp"
    tools:context=".MainActivity"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:textSize="25dp"
        android:text="Click to change this text color..."
        android:clickable="true"
        android:onClick="onTextViewClicked"
        />
</RelativeLayout>
MainActivity.java (Partial code)

public void onTextViewClicked(View v){
 //Get widgets reference from XML layout
 final TextView tv = (TextView) findViewById(R.id.tv);

 //Initialize a new AlertDialog Builder
 AlertDialog.Builder adb = new AlertDialog.Builder(this);

 //Set a title for alert dialog
 adb.setTitle("Choose a color");

 //Initialize a new String Array
 final String[] Colors = new String[]{
   // Those color names are supported by
   //Android parseColor() method
   "Olive","Navy","Purple","Maroon",
 };

 //Set a list of items to be displayed in the dialog as the content
 //It will render a single choice traditional list on alert dialog
 adb.setItems(Colors, new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int which) {
   //This 'which' argument carry the list selected item's index position
   String clickedItemValue = Arrays.asList(Colors).get(which);
   //Set the TextView text color corresponded to the user selected color
   tv.setTextColor(Color.parseColor(clickedItemValue));
  }
 });

 //Display the Alert Dialog on app interface
 adb.show();
}
Additional imported classes

import android.content.DialogInterface;
import android.widget.TextView;
import android.view.View;
import android.app.AlertDialog;
import java.util.Arrays;


4. Multiple Choice Alert Dialog (CheckBoxes on AlertDialog)

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:padding="16dp"
    tools:context=".MainActivity"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:textSize="15dp"
        android:text="Click to choose your favorite colors..."
        android:clickable="true"
        android:onClick="onTextViewClicked"
        />
</RelativeLayout>
MainActivity.java (Partial code)

public void onTextViewClicked(View v){
 //Get widgets reference from XML layout
 final TextView tv = (TextView) findViewById(R.id.tv);

 //Initialize a new AlertDialog Builder
 AlertDialog.Builder adb = new AlertDialog.Builder(this);

 //Set a title for alert dialog
 adb.setTitle("Choose your favorite colors");

 //Initialize a new String Array
 final String[] Colors = new String[]{
   "HoneyDew","Indigo","Ivory","FireBrick","Crimson"
 };

 //ArrayList to store Alert Dialog selected items index position
 final ArrayList<Integer> selectedItems = new ArrayList<Integer>();

 //Array to store pre checked/selected items
 final boolean[] preCheckedItems = new boolean[]{
   false,false,false,false,false
 };

 //Define the AlertBuilder as a multiple choice items collection.
 /*
  AlertDialog.builder.setMultiChoiceItems() method
  setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems,
  DialogInterface.OnMultiChoiceClickListener listener)

  First argument to pass an Array of items

  Second argument pass the pre checked/selected items.
  if we don't want to display any pre checked items,
  We can pass the second parameter value as null.

  Third argument set a Click Listener for Multiple Choice.
  */
 adb.setMultiChoiceItems(Colors, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener(){
  @Override
  public void onClick(DialogInterface dialog, int which, boolean isChecked){

     //You can update the preCheckedItems array here
   //In this tutorial i ignored this feature
   if(isChecked)
   {
    //Add the checked item to checked items collection
    selectedItems.add(which);
   }
   else if(selectedItems.contains(which))
   {
    /*If the clicked checkbox item is unchecked now
     and it already contains in the selected items collection
     then we remove it from selected items collection*/
    selectedItems.remove(which);
   }
  }
 });

 //Define the AlertDialog positive/ok/yes button
 adb.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
    @Override
  public void onClick(DialogInterface dialog, int which){
   //When user click the positive button from alert dialog

     //Set a message to show user at top
     tv.setText("Your preferred colors are...\n");

     //Loop/iterate through ArrayList
     for(int i=0;i<selectedItems.size();i++){
      //selectedItems ArrayList current item's correspondent
      //index position of Colors Array
      int IndexOfColorsArray = selectedItems.get(i);

      //Get the selectedItems array specific index position's
      //corresponded item from Colors array
      String selectedColor = Arrays.asList(Colors).get(IndexOfColorsArray);

      //Display the selected colors to TextView
      tv.setText(tv.getText() +  selectedColor + "\n");
     }

     //Write a message for user
     String message = "You can change selection by clicking it again...";
     //Display the additional message to user on new line
     tv.setText(tv.getText() + "\n\n" + message);
    }
 });

 //Define the Neutral/Cancel button in AlertDialog
 adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener(){
  @Override
  public void onClick(DialogInterface dialog, int which){
   //When user click the neutral/cancel button from alert dialog
  }
 });

 //Display the Alert Dialog on app interface
 adb.show();
}
Additional imported classes

import android.content.DialogInterface;
import android.widget.TextView;
import android.view.View;
import android.app.AlertDialog;
import java.util.Arrays;
import java.util.ArrayList;



More android examples