RSS Feed Alexander Cremer on Twitter Alexander Cremer on Google Plus Alexander Cremer on Vizify

Android code snippet - Custom datepicker dialog

from category Android

Introduction

The following article provides a quick introduction on using a custom dialog, especially a datepicker dialog in Android. The example provides a possible solution to exlude specific days from users selection, e.g. you can prevent the user to choose a date of a sunday.

ImageCenterAlignmentScaled

Prerequisites

You need basic experience in Android development and you should be able to create a sample app project where you can paste and test the provided code. I recommend to use Android Studio though its still in an early stage but it works like a charm for me already.

Hands on

Define a layout for your custom dialog e.g. datepicker

Define custom layout with all UI elements, that you want to be included in your custom dialog. The following example provides a layout for a datepicker as shown in the screenshots above.

<!-- res/layout/datepicker_layout.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="wrap_content"
              android:orientation="vertical">
 
    <TextView
            android:id="@+id/dialog_dateview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:layout_margin="12dp"
            android:text=""
            android:layout_gravity="center"/>
 
    <DatePicker
            android:id="@+id/dialog_datepicker"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:calendarViewShown="false"/>
 
</LinearLayout>

Create a datepicker dialog based on a custom layout

The following code builds a dialog based on the above defined layout and shows it. Further more the example contains the functionality to prevent the user from choosing a date before the 12.12.2010 or to choose a date on weekday sunday. This can be customized for any other desired use case.

/* java/de.opensourced.datepickertest/DatePickerTestActivity.java */
public class DatePickerTestActivity extends Activity {
 
Button datePickerShowDialogButton = null;
 
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datepickertest);
        // Button to show datepicker
        datePickerShowDialogButton = 
        (Button) actionBar.getCustomView().findViewById(
           R.id.activity_datepickertest_datebutton
        );
        datePickerShowDialogButton.setOnClickListener(
          new View.OnClickListener() {
             public void onClick(View v) {
                 showDatePicker();
             }
          });
    }
 
    /**
     * Builds a custom dialog based on the defined layout 
     * 'res/layout/datepicker_layout.xml' and shows it
     */
    public void showDatePicker() {
        // Initializiation
        LayoutInflater inflater = (LayoutInflater) getLayoutInflater();
        final AlertDialog.Builder dialogBuilder = 
        new AlertDialog.Builder(this);
        View customView = inflater.inflate(R.layout.datepicker_layout, null);
        dialogBuilder.setView(customView);
        Calendar now = Calendar.getInstance();
        final DatePicker datePicker = 
            (DatePicker) customView.findViewById(R.id.dialog_datepicker);
        final TextView dateTextView = 
            (TextView) customView.findViewById(R.id.dialog_dateview);
        final SimpleDateFormat dateViewFormatter = 
            new SimpleDateFormat("EEEE, dd.MM.yyyy", Locale.GERMANY);
        final SimpleDateFormat formatter = 
            new SimpleDateFormat("dd.MM.yyyy", Locale.GERMANY);
        // Minimum date
        Calendar minDate = Calendar.getInstance();
        try {
            minDate.setTime(formatter.parse("12.12.2010"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        datePicker.setMinDate(minDate.getTimeInMillis());
        // View settings
        dialogBuilder.setTitle("Choose a date");
        Calendar choosenDate = Calendar.getInstance();
        int year = choosenDate.get(Calendar.YEAR);
        int month = choosenDate.get(Calendar.MONTH);
        int day = choosenDate.get(Calendar.DAY_OF_MONTH);
        try {
            Date choosenDateFromUI = formatter.parse(
                datePickerShowDialogButton.getText().toString()
            );
            choosenDate.setTime(choosenDateFromUI);
            year = choosenDate.get(Calendar.YEAR);
            month = choosenDate.get(Calendar.MONTH);
            day = choosenDate.get(Calendar.DAY_OF_MONTH);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Calendar dateToDisplay = Calendar.getInstance();
        dateToDisplay.set(year, month, day);
        dateTextView.setText(
            dateViewFormatter.format(dateToDisplay.getTime())
        );
        // Buttons
        dialogBuilder.setNegativeButton(
            "Go to today", 
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    datePickerShowDialogButton.setText(
                        formatter.format(now.getTime())
                    );
                    dialog.dismiss();
                }
            }
        );
        dialogBuilder.setPositiveButton(
            "Choose", 
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Calendar choosen = Calendar.getInstance();
                    choosen.set(
                        datePicker.getYear(), 
                        datePicker.getMonth(), 
                        datePicker.getDayOfMonth()
                    );
                    datePickerShowDialogButton.setText(
                        dateViewFormatter.format(choosen.getTime())
                    );
                    dialog.dismiss();
                }
            }
        );
        final AlertDialog dialog = dialogBuilder.create();
        // Initialize datepicker in dialog atepicker
        datePicker.init(
            year, 
            month, 
            day, 
            new DatePicker.OnDateChangedListener() {
                public void onDateChanged(DatePicker view, int year, 
                    int monthOfYear, int dayOfMonth) {
                    Calendar choosenDate = Calendar.getInstance();
                    choosenDate.set(year, monthOfYear, dayOfMonth);
                    dateTextView.setText(
                        dateViewFormatter.format(choosenDate.getTime())
                    );
                    if (choosenDate.get(Calendar.DAY_OF_WEEK) == 
                        Calendar.SUNDAY || 
                        now.compareTo(choosenDate) < 0) {
                        dateTextView.setTextColor(
                            Color.parseColor("#ff0000")
                        );
                        ((Button) dialog.getButton(
                        AlertDialog.BUTTON_POSITIVE))
                            .setEnabled(false);
                    } else {
                        dateTextView.setTextColor(
                            Color.parseColor("#000000")
                        );
                        ((Button) dialog.getButton(
                        AlertDialog.BUTTON_POSITIVE))
                            .setEnabled(true);
                    }
                }
            }
        );
        // Finish
        dialog.show();
    }
}

You can use the following layout for a test activity:

<!-- res/layout/activity_datepickertest.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=".DatePickerTestActvity">
 
    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button_initialLabel"
            android:id="@+id/activity_datepickertest_datebutton"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"/>
</RelativeLayout>

tag icon [Android custom dialog datepicker exclusion day date no sundays code snippet]

added on 2014-01-21



Comments from users

comment written by [on error] on 2014-08-27 09:23

datePickerShowDialogButton = 
        (Button) actionBar.getCustomView().findViewById(
           R.id.activity_datepickertest_datebutton
        );

comment written by [on error] on 2014-08-27 09:21

 datePickerShowDialogButton = 
        (Button) actionBar.getCustomView().findViewById(
           R.id.activity_datepickertest_datebutton
        );

comment written by [jydimir] on 2014-07-16 10:50

Thanks, really helpful

comment written by [alex] on 2014-03-10 12:00

@Priya: If you still have problems regarding the quoted line please post the error stack trace

comment written by [Priya] on 2014-03-08 10:46

Thanks for your code.. was searching since many days to display date picker on fragment.. using your code solved my problem...

comment written by [Priya] on 2014-03-08 10:27

Thanks for this example.. 
how to implement it on Fragment...
getting error at
Date choosenDateFromUI = formatter						.parse(datePickerShowDialogButton.getText().toString());

comment written by [alex] on 2014-01-21 10:06

@nodate: I don't think this is possible with the standard control, you have to create your own custom control for this purpose.

@javaDroid: "datePickerButton" was wrong, i corrected it, thanks for the feedback!

comment written by [nodate] on 2013-12-29 20:47

This is working well, but how to hide day selection in this example? I need only month and year selections.

comment written by [javaDroid] on 2013-11-21 08:11

thanks . It was very usefull. but i didnt understand what "datePickerButton" is . could you tell what is this where was it initiated ?  

comment written by [tfm] on 2013-11-19 20:55

Very nice example.  Thanks.



Leave a comment...


pseudonym:



your comment (max 600 characters):


characters left


captcha image

(please type text from image for verification in textbox below)

captchatext:






Twitter Logo

My latest tweets