Skip to main content

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

Popular posts from this blog

How to use NumberPicker in Android

Table of contentsNumberPicker ExamplesetOnValueChangedListeneronValueChange()setWrapSelectorWheel()setMinValue()setMinValue()setMaxValue()NumberPicker with String ArraysetDisplayedValues()String Array1. NumberPicker Example activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity" android:background="#ffffff" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25dp" android:text="Select a number..." /> <NumberPicker android:id="@+id/np" …

TextView new line (multiline) in android

TextView new line (multiline) TextView display text on android app. by default, TextView show text on a single line, and if it is long then TextView take more lines to display its text. android developers can generate a new line on TextView both programmatically and syntactically. android developers can make a multiline TextView without splitting text to multiline by android:minLines attribute.

the following android example code demonstrate us how can we syntactically create a new line on TextView widget by xml layout file and string resource file.

the simplest way to create a new line on TextView is android:text attribute. android:text attribute allow us to display text on android app. we can add a simple '\n' to TextView text where we want to start a new line. in this way we can create a multiline TextView widget in android app. we can assign android:text attribute value by this way android:text="Line1 \n Line2 \n Line3" for a TextView widget. this value will…

How to change TextView font size in android

TextView font size TextView widget display text on android application. we can set or change TextView font size statically by declarative syntax in xml layout file or programmatically at run time in java file. even we can use an xml file source to define font size.

the following example code demonstrate us how can we define TextView font size in xml layout file and how can we uses dimens.xml to reference font size. in this example we did not changes any coding in java file, so here we only include the layout xml file and dimens.xml file. activity_main.xml <LinearLayout 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:orientation="vertical" android:layout_margin="25dp" tools:context=".MainActivity" > <TextView android:id=&…