In this tutorial we will discuss how to use dialogs and alerts in Android Apps.
A Dialog is a small popup shown to the user to get some additional information from the user or ask him to make some decision. Alert dialog box in android can be used as a confirm alert, while user is deleting something as shown in figure below.
It can also be used for getting some information in android apps or creating custom dialog in your android application. We will be discussing three classes AlertDialog,DatePickerDialog
and TimePickerDialog
. All of these classes extends the base class Dialog
.
AlertDialog
can show title, three buttons, a list of items, or any custom layout .
DatePickerDialog
and TimePickerDialog
have a pre-defined UI that allows the user to select a date and time respectively.
We will use DialogFragment
for creating the dialogs. The DialogFragment class provides everything you will need to create and manage a Dialog
object.
Prerequisites
- We hope you have installed Android Studio.
- Also before going through this tutorial we suggest you make a simple Hello World App and run it on your smartphone.
So now let’s create our Alert Dialog Application. Start by creating a new project in Android Studio as follows.
Creating a new project
Please follow the steps:
- Open Android Studio and create a new project by going to File => New => New Project. Enter the Application Name as
AlertDialog
and your company domain name. (We have used our company domain i.e androidtutorialpoint.com. Similarly you can use yours). - Click Next and choose Minimum SDK. We have kept the default setting and click Next.
- Choose Empty Activity and click next.
- In the next screen enter Activity Name as MainActivity and remember to check the Generate Layout Button and then click Finish.
Gradle will sync the project and resolve all the dependencies.
Alert Dialog with Single Button
Create a new java class SingleButtonFragment.java
and put the following code.
SingleButtonFragment.java
package com.androidtutorialpoint.alertdialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
public class SingleButtonFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_single_button)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getActivity(),"You clicked yes",Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
This class extends DialogFragment
. As discussed above, It provides methods to manage the AlertDialog
. onCreateDialog()
is a callback method that to instantiate and returns a Dialog
class object.
The AlertDialog.Builder
class you to create an AlertDialog with these kinds of content, including a custom layout.
In this tutorial we are going to use the following methods from this class .
setMessage()
– Set the given resource id as the message that is shown to the user. setPositiveButton()
– Set the listener that is called when the positive button is pressed. Positive Button means the buttons which refers to a Positive response, for example- OK or Yes Button. setNegativeButton()
– Set the listener that is called when the negative button is pressed. Negative Button means the buttons which refers to a negative response, for example- Cancel or No Button. setNeutralButton()
– Set the listener that is called when the neutral button is pressed. Neutral Button means the buttons which refers to a neutral response, for example- Remind Me Later or Don’t know kind of responses.
In the SingleButtonFragment
we have only positive button on clicking the button a positive message is shown. Note that we are just showing a message, when the button is pressed, generally you will perform some action based upon the button pressed.
Alert Dialog with Two Buttons
Create a new java class TwoButtonFragment.java and put the following code.
TwoButtonFragment.java
package com.androidtutorialpoint.alertdialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
public class TwoButtonFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_two_button)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getActivity(),"You clicked Yes !!",Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getActivity(),"You clicked No !!",Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
This class is almost similar to SingleButtonFragment.java however, we have added one negative button in order to perform some negative action or show the negative message.
On clicking the positive button a positive message is shown while on clicking the negative button a negative message is shown. Again we are just showing messages for the demonstration purpose, you can perform some action based upon which button is pressed.
Alert Dialog with Three Buttons
Create a new java class ThreeButtonFragment.java and put the following code.
ThreeButtonFragment.java
package com.androidtutorialpoint.alertdialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
public class ThreeButtonFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_three_button)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getActivity(),"You clicked Yes <img alt="🙂" class="wp-smiley" src="https:
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getActivity(),"You clicked No <img alt="🙁" class="wp-smiley" src="https:
}
})
.setNeutralButton(R.string.remind, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(),"You clicked Remind Me Later !! \n We will Remind you later ",Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
This class is again similar to SingleButtonFragment.java however, we have added one negative button and one neutral button.
On clicking the positive button a positive message is shown while on clicking the negative button a negative message is shown. Additionally, there is a neutral button to give a neutral response.
Alert Dialog with Single Choice List
Create a new java class SingleChoiceListFragment.java and put the following code.
SingleChoiceListFragment.java
package com.androidtutorialpoint.alertdialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
public class SingleChoiceListFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_dish)
.setItems(R.array.dish_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(), "You clicked " + getResources().getStringArray(R.array.dish_array)[which], Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
In this class, we are using setItems()
to create a single choice list. Instead of setting the message, only setting the title is required here. For that we are using setTitle()
function.
In the setItems()
we pass resource Id for array and set the OnClickListener()
method, as soon as the user clicks on one of the choice this listener is called. The index of the item clicked is stored in the int argument which.
Here we are showing the element clicked by the user by accessing the index which in array using
getResources().getStringArray(R.array.dish_array)[which]
Create a resource file arrays.xml under the values folder and put the following contents.
="1.0"="utf-8"
<resources>
<string-array name="dish_array">
<item>Pizza</item>
<item>Pasta</item>
<item>Sandwich</item>
</string-array>
</resources>
Alert Dialog with Single Choice Radion Buttons List
Create a new java class SingleChoiceRadioButtonListFragment.java and put the following code.
SingleChoiceRadioButtonListFragment.java
package com.androidtutorialpoint.alertdialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
public class SingleChoiceRadioButtonListFragment extends DialogFragment {
private int mSelectedItem;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_dish)
.setSingleChoiceItems(R.array.dish_array, 0,
new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
mSelectedItem = which;
}
})
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getActivity(), "You selected !! \n " + getResources().getStringArray(R.array.dish_array)[mSelectedItem], Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getActivity(), "You clicked Cancel \n No Item was selected !!", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
In this class, we are using setSingleChoiceItems()
to create a single choice list with radio buttons. The first argument is the array resource, next we have the position of the item which is checked by default, If -1 is specified then no item will be checked. Third argument is an OnClickListener()
which is called when the user clicks on the item. Here we are simply setting the local variable mSelectedItem
to the index that was selected.
We have added a positive and a negative button. On clicking, the positive button the item that is selected is shown. On clicking the cancel button, a toast is shown that no item has been selected.
Alert Dialog with Multiple Choice Check Box List
Create a new java class MultipleChoiceCheckBoxListFragment.java and put the following code.
MultipleChoiceCheckBoxListFragment.java
package com.androidtutorialpoint.alertdialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class MultipleChoiceCheckBoxListFragment extends DialogFragment {
private ArrayList<Integer> mSelectedItems;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_dish)
.setMultiChoiceItems(R.array.dish_array, null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
String s = "";
for(int i:mSelectedItems){
s += getResources().getStringArray(R.array.dish_array)[i];
s +="\n";
}
Toast.makeText(getActivity(), "You selected !! \n "+s, Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getActivity(), "You clicked Cancel \n No Item was selected !!", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
In this class, we are using setMultiChoiceItems()
to create a multiple choice list with check boxes. Again the first argument is the array resource, second argument specifies the item which is checked by default, null is provided to uncheck all boxes. Third argument is an OnClickListener()
which is called when the user clicks on the item.We are adding the items an ArrayList of type Integer.
We have added a positive and a negative button. On clicking, the positive button all the items that were selected are shown. On clicking the cancel button, a toast is shown that no item has been selected.
Working with DatePicker
Date Picker are used to allow the user to select a date (month, day, year) by showing a calendar view as shown in the video above. Date Picker is used in travel apps to select the boarding date, in a reminder app to select the reminder date and many other apps.
In this tutorial we will be using a DatePicker Widget in our layout file and then inflate that view to get a DatePicker Dialog.
Create a new layout file dialog_date.xml and add the following code.
dialog_date.xml
<DatePicker xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/dialog_date_date_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
DatePickerFragment.java
package com.androidtutorialpoint.alertdialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import java.util.Date;
import java.util.GregorianCalendar;
public class DatePickerFragment extends DialogFragment {
private DatePicker datePicker;
public interface DateDialogListener {
void onFinishDialog(Date date);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
View v = LayoutInflater.from(getActivity())
.inflate(R.layout.dialog_date,null);
datePicker = (DatePicker) v.findViewById(R.id.dialog_date_date_picker);
return new android.support.v7.app.AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int year = datePicker.getYear();
int mon = datePicker.getMonth();
int day = datePicker.getDayOfMonth();
Date date = new GregorianCalendar(year,mon,day).getTime();
DateDialogListener activity = (DateDialogListener) getActivity();
activity.onFinishDialog(date);
dismiss();
}
})
.create();
}
}
First, we inflate the dialog_date.xml. Then reference the datePicker
. Then we create and return a AlertDialog
which is shown to the user. We have used the setView()
method to set the inflated view. When the user clicks OK button of the DatePicker dialog
first we pick the year, month and the day from the datePicker
then we create a date object and intialize it using the picked values. We also deliver the event to the hosting activity, that is the MainActivity
in our case.
To do this we have defined an interface DateDialogListener
with a method for each type of click event. Then implement that interface in the host activity that will receive the action events from the dialog.
We will talk about implementing the DateDialogListener
in a while when we discuss the MainActivity
code.
Working with TimePicker
Time Picker are used to allow the user to select a time (hour,minute) by showing a clock type view as shown in the video above. Time Picker is mostly used in the Alarm or reminder apps.
For TimePicker also, we will be using a TimePicker Widget in our layout file and then inflate that view to get a TimePicker Dialog.
Create a new layout file dialog_time.xml and add the following code.
dialog_time.xml
<TimePicker xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/dialog_time_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
TimePickerFragment.java
package com.androidtutorialpoint.alertdialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TimePicker;
public class TimePickerFragment extends DialogFragment {
private TimePicker timePicker;
public interface TimeDialogListener {
void onFinishDialog(String time);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
View v = LayoutInflater.from(getActivity())
.inflate(R.layout.dialog_time,null);
timePicker = (TimePicker) v.findViewById(R.id.dialog_time_picker);
return new android.support.v7.app.AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.time_picker_title)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int hour = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
hour = timePicker.getHour();
}else{
hour = timePicker.getCurrentHour();
}
int minute = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
minute = timePicker.getMinute();
}else{
minute = timePicker.getCurrentMinute();
}
TimeDialogListener activity = (TimeDialogListener) getActivity();
activity.onFinishDialog(updateTime(hour,minute));
dismiss();
}
})
.create();
}
private String updateTime(int hours, int mins) {
String timeSet = "";
if (hours > 12) {
hours -= 12;
timeSet = "PM";
} else if (hours == 0) {
hours += 12;
timeSet = "AM";
} else if (hours == 12)
timeSet = "PM";
else
timeSet = "AM";
String minutes = "";
if (mins < 10)
minutes = "0" + mins;
else
minutes = String.valueOf(mins);
String myTime = new StringBuilder().append(hours).append(':')
.append(minutes).append(" ").append(timeSet).toString();
return myTime;
}
}
First, we inflate the dialog_time.xml. Then reference the timePicker
. Then we create and return a AlertDialog
which is shown to the user. We have used the setView()
as in the datePicker method to set the inflated view. When the user clicks OK button of the TimePicker dialog first we pick the hour and minute. For picking up the hour, we are using the timePicker.getHour()
for phone supporting android API 23(Android Marshmallow) and timePicker.getCurrentHour()
for the earlier versions. Then we create a String object myTime
based upon the value of hour and minute. We also deliver the event to the hosting activity, that is the MainActivity
in our case.
To do this we have defined an interface TimeDialogListener
with a method for each type of click event. We need to implement this interface in the host activity that will receive the action events from the dialog.
Showing the Dialogs
To display the dialog, we create an instance of DialogFragment
and call show()
, passing the FragmentManager and a tag name for the dialog fragment.
The tag is used by the system to save and restore the fragment state when necessary. It also allows us to get a handle to the fragment by using findFragmentByTag()
.
First open the layout file for the MainActivity
i.e activity_main.xml and add the following code.
activity_main.xml
="1.0"="utf-8"
<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: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">
<Button
android:id="@+id/alert_dialog_one_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Alert Dialog with one button"
android:padding="20dp"/>
<Button
android:id="@+id/alert_dialog_two_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Alert Dialog with two button"
android:padding="20dp"/>
<Button
android:id="@+id/alert_dialog_three_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Alert Dialog with three button"
android:padding="20dp"/>
<Button
android:id="@+id/alert_dialog_single_choice_list_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Single Choice Dialog"
android:padding="20dp"/>
<Button
android:id="@+id/alert_dialog_single_choice_radio_button_list_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Single Choice Radio Button Dialog"
android:padding="20dp"/>
<Button
android:id="@+id/alert_dialog_multiple_choice_check_box_list_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Multiple Choice Check Box Dialog"
android:padding="20dp"/>
<Button
android:id="@+id/alert_dialog_date_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Date Picker Dialog"
android:padding="20dp"/>
<Button
android:id="@+id/alert_dialog_time_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Time Picker Dialog"
android:padding="20dp"/>
</LinearLayout>
We have created buttons to demonstrate different types of AlertDialogs
we have discussed above.
Open the file MainActivity.java and add the following code.
MainActivity.java.
package com.androidtutorialpoint.alertdialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity implements DatePickerFragment.DateDialogListener,TimePickerFragment.TimeDialogListener {
private static final String DIALOG_DATE = "MainActivity.DateDialog";
private static final String DIALOG_TIME = "MainActivity.TimeDialog";
private static final String DIALOG_SINGLE_BUTTON = "MainActivity.SingleButtonDialog";
private static final String DIALOG_TWO_BUTTON = "MainActivity.TwoButtonDialog";
private static final String DIALOG_THREE_BUTTON = "MainActivity.ThreeButtonDialog";
private static final String DIALOG_SINGLE_CHOICE_LIST = "MainActivity.SingleChoiceListDialog";
private static final String DIALOG_SINGLE_CHOICE_RADIO_BUTTON_LIST = "MainActivity.SingleChoiceRadioButtonListDialog";
private static final String DIALOG_MULTIPLE_CHOICE_CHECK_BOX_LIST = "MainActivity.MultipleChoiceCheckBoxListDialog";
private Button singleButtonAlertDialog;
private Button twoButtonAlertDialog;
private Button threeButtonAlertDialog;
private Button datePickerAlertDialog;
private Button timePickerAlertDialog;
private Button singleChoiceListAlertDialog;
private Button singleChoiceRadioButtonAlertDialog;
private Button multipleChoiceCheckBoxAlertDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
singleButtonAlertDialog = (Button)findViewById(R.id.alert_dialog_one_button);
twoButtonAlertDialog = (Button)findViewById(R.id.alert_dialog_two_button);
threeButtonAlertDialog = (Button)findViewById(R.id.alert_dialog_three_button);
datePickerAlertDialog = (Button)findViewById(R.id.alert_dialog_date_picker);
timePickerAlertDialog = (Button)findViewById(R.id.alert_dialog_time_picker);
singleChoiceListAlertDialog = (Button)findViewById(R.id.alert_dialog_single_choice_list_button);
singleChoiceRadioButtonAlertDialog = (Button)findViewById(R.id.alert_dialog_single_choice_radio_button_list_button);
multipleChoiceCheckBoxAlertDialog = (Button)findViewById(R.id.alert_dialog_multiple_choice_check_box_list_button);
singleButtonAlertDialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SingleButtonFragment dialog = new SingleButtonFragment();
dialog.show(getSupportFragmentManager(), DIALOG_SINGLE_BUTTON);
}
});
twoButtonAlertDialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TwoButtonFragment dialog = new TwoButtonFragment();
dialog.show(getSupportFragmentManager(), DIALOG_TWO_BUTTON);
}
});
threeButtonAlertDialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ThreeButtonFragment dialog = new ThreeButtonFragment();
dialog.show(getSupportFragmentManager(), DIALOG_THREE_BUTTON);
}
});
datePickerAlertDialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatePickerFragment dialog = new DatePickerFragment();
dialog.show(getSupportFragmentManager(), DIALOG_DATE);
}
});
timePickerAlertDialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TimePickerFragment dialog = new TimePickerFragment();
dialog.show(getSupportFragmentManager(), DIALOG_TIME);
}
});
singleChoiceListAlertDialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SingleChoiceListFragment dialog = new SingleChoiceListFragment();
dialog.show(getSupportFragmentManager(), DIALOG_SINGLE_CHOICE_LIST);
}
});
singleChoiceRadioButtonAlertDialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SingleChoiceRadioButtonListFragment dialog = new SingleChoiceRadioButtonListFragment();
dialog.show(getSupportFragmentManager(), DIALOG_SINGLE_CHOICE_RADIO_BUTTON_LIST);
}
});
multipleChoiceCheckBoxAlertDialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MultipleChoiceCheckBoxListFragment dialog = new MultipleChoiceCheckBoxListFragment();
dialog.show(getSupportFragmentManager(), DIALOG_MULTIPLE_CHOICE_CHECK_BOX_LIST);
}
});
}
@Override
public void onFinishDialog(Date date) {
Toast.makeText(this, "Selected Date :"+ formatDate(date), Toast.LENGTH_SHORT).show();
}
public String formatDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String hireDate = sdf.format(date);
return hireDate;
}
@Override
public void onFinishDialog(String time) {
Toast.makeText(this, "Selected Time : "+ time, Toast.LENGTH_SHORT).show();
}
}
Note that the MainActivity
implements the interfaces DatePickerFragment.DateDialogListener
and TimePickerFragment.TimeDialogListener
we defined in the datePickerFragment
and timePickerFragment
.
The MainActivity
code is very simple first we have defined unique tags for each type of AlertDialog
. Next we are referencing the buttons from the layout. In the OnClickListener()
we are showing the AlertDialog
.
At last we have two methods onFinishDialog(Date date)
to handle the datePicker
events and onFinishDialog(String time)
to handle the timePicker
events.
In these methods, we are simply showing the date and time respectively to the user via a toast message.
We have used the following string resources, open your strings.xml and put the following strings.
strings.xml
<resources>
<string name="app_name">AlertDialog</string>
<string name="date_picker_title">Select Date</string>
<string name="cancel">Cancel</string>
<string name="dialog_single_button">Isn\'t This Tutorial Great !!</string>
<string name="no">No</string>
<string name="yes">Yes</string>
<string name="dialog_two_button">Are you a professional Android Developer ?</string>
<string name="dialog_three_button">Did you subscribe to Android Tutorial Point ?</string>
<string name="remind">Remind Me Later</string>
<string name="pick_dish">What is your favourite Dish ?</string>
<string name="ok">OK</string>
<string name="time_picker_title">Select Time</string>
</resources>
Now run the app and experiment with different types of AlertDialogs
. You can also use custom layouts for finer control over the dialogs shown to the user for example, you may have an android dialog with EditText
to get user input.