Blog Archive

Android activity for DatePickerDialog, TimePickerDialog and CalendarView widget

A dialog is usually a small window that appears in front of the current Activity. The underlying Activity loses focus and the dialog accepts all user interaction. Dialogs are normally used for notifications that should interupt the user and to perform short tasks that directly relate to the application in progress (such as a progress bar or a login prompt).

The Dialog class is the base class for creating dialogs. However, you typically should not instantiate a Dialog directly. Instead, you should use one of the following subclasses:
  • AlertDialog
    • A dialog that can manage zero, one, two, or three buttons, and/or a list of selectable items that can include checkboxes or radio buttons. The AlertDialog is capable of constructing most dialog user interfaces and is the suggested dialog type. 
  • ProgressDialog
    • A dialog that displays a progress wheel or progress bar. Because it's an extension of the AlertDialog, it also supports buttons. 
  • DatePickerDialog
    • A dialog that allows the user to select a date. 
  • TimePickerDialog
    • A dialog that allows the user to select a time. 


Android DatePickerDialog TimePickerDialog and CalendarView widget
Android DatePickerDialog TimePickerDialog and CalendarView widget
Android DatePickerDialog TimePickerDialog and CalendarView widget
Android DatePickerDialog TimePickerDialog and CalendarView widget

Source for AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.as400samplecode" android:versionCode="1"
    android:versionName="1.0">
    <uses-sdk android:minSdkVersion="12" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidDialogs" android:label="@string/app_name"
            android:theme="@android:style/Theme.Holo.Light">
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MyCalendar" android:theme="@style/MyTheme" />
    </application>
</manifest>

Source for styles.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyTheme" parent="@android:style/Theme.Holo.Light">
        <item name="android:windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>
    </style>
</resources>

Source for main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:orientation="horizontal" android:gravity="center" android:id="@+id/layout1">
    <TableLayout android:layout_height="match_parent"
        android:layout_width="wrap_content" android:id="@+id/tableLayout1">
        <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:textSize="25sp"
                android:id="@+id/dateText" android:text="Android Dialog Date:" />
            <EditText android:text="EditText" android:layout_height="wrap_content"
                android:id="@+id/dateDisplay" android:layout_width="wrap_content"
                android:inputType="date" android:textStyle="bold" android:enabled="false" />
            <Button android:layout_width="wrap_content" android:id="@+id/pickDate"
                android:textSize="12sp" android:text="Change Date"
                android:layout_height="wrap_content" />
        </TableRow>
        <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:textSize="25sp"
                android:id="@+id/dateText" android:text="Calendar View Date:" />
            <EditText android:text="EditText" android:layout_height="wrap_content"
                android:id="@+id/dateDisplay2" android:layout_width="wrap_content"
                android:inputType="date" android:textStyle="bold" android:enabled="false" />
            <Button android:layout_width="wrap_content" android:id="@+id/pickDate2"
                android:textSize="12sp" android:text="Change Date"
                android:layout_height="wrap_content" />
        </TableRow>
        <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:textSize="25sp"
                android:id="@+id/dateText" android:text="Android Dialog Time:" />
            <EditText android:text="EditText" android:layout_height="wrap_content"
                android:id="@+id/timeDisplay" android:layout_width="wrap_content"
                android:inputType="date" android:textStyle="bold" android:enabled="false" />
            <Button android:layout_width="wrap_content" android:id="@+id/pickTime"
                android:textSize="12sp" android:text="Change Time"
                android:layout_height="wrap_content" />
        </TableRow>
    </TableLayout>

</LinearLayout>

Source for mycalendar.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:layout_width="wrap_content"
    android:layout_height="match_parent" android:id="@+id/frameLayout1"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <CalendarView android:id="@+id/calendarView1"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />
</FrameLayout>

Source for MyCalendar.java

package com.as400samplecode;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.CalendarView;

public class MyCalendar extends Activity {

    private int mYear;
    private int mMonth;
    private int mDay;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CalendarView calendar = new CalendarView(this);
        calendar.setOnDateChangeListener(mDateSetListener);
        setContentView(calendar);

    }

    // the callback received when the user "sets" the date in the dialog
    private CalendarView.OnDateChangeListener mDateSetListener =
        new CalendarView.OnDateChangeListener() {

        public void onSelectedDayChange(CalendarView view, int year, 
                int monthOfYear, int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            String selectedDate = new StringBuilder().append(mMonth + 1).append("/").append(mDay).append("/")
            .append(mYear).append(" ").toString();

            Bundle b = new Bundle();
            b.putString("dateSelected", selectedDate);

            //Add the set of extended data to the intent and start it
            Intent intent = new Intent();
            intent.putExtras(b);
            setResult(RESULT_OK,intent);       
            finish();
        }
    };

}

Source for AndroidDialogs.java

package com.as400samplecode;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

public class AndroidDialogs extends Activity {

    private EditText mDateDisplay;
    private Button mPickDate;

    private EditText mDateDisplay2;
    private Button mPickDate2;

    private int mYear;
    private int mMonth;
    private int mDay;

    private EditText mTimeDisplay;
    private Button mPickTime;

    private int mHour;
    private int mMinute;

    static final int DATE_DIALOG_ID = 0;
    static final int CALENDAR_VIEW_ID = 1;
    static final int TIME_DIALOG_ID = 2;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.optionsmenu, menu);
        return true;

    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // capture our View elements
        mDateDisplay = (EditText) findViewById(R.id.dateDisplay);
        mPickDate = (Button) findViewById(R.id.pickDate);
        mDateDisplay2 = (EditText) findViewById(R.id.dateDisplay2);
        mPickDate2 = (Button) findViewById(R.id.pickDate2);
        mTimeDisplay = (EditText) findViewById(R.id.timeDisplay);
        mPickTime = (Button) findViewById(R.id.pickTime);


        // add a click listener to the select a date button
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        // add a click listener to the select a calendar date button 
        mPickDate2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                Intent intent = new Intent(AndroidDialogs.this, MyCalendar.class); 
                startActivityForResult(intent,CALENDAR_VIEW_ID); 
            }


        });

        // add a click listener to the button
        mPickTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });




        // get the current date and time
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);

        // display the current date 
        displayDate();
        displayCalendarViewDate();

        // display the current time
        displayTime();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        switch(requestCode) {
        case CALENDAR_VIEW_ID: 
            if (resultCode == RESULT_OK) {

                Bundle bundle = data.getExtras();

                mDateDisplay2 = (EditText) findViewById(R.id.dateDisplay2);
                mDateDisplay2.setText(bundle.getString("dateSelected"));
                break;
            }
        }

    }  

    // updates the date in the EditText
    private void displayDate() {
        mDateDisplay.setText(
                new StringBuilder()
                // Month is 0 based so add 1
                .append(mMonth + 1).append("/")
                .append(mDay).append("/")
                .append(mYear).append(" "));
    }

    // updates the date in the EditText
    private void displayCalendarViewDate() {
        mDateDisplay2.setText(
                new StringBuilder()
                // Month is 0 based so add 1
                .append(mMonth + 1).append("/")
                .append(mDay).append("/")
                .append(mYear).append(" "));
    }

    // updates the time we display in the EditText
    private void displayTime() {
        mTimeDisplay.setText(
                new StringBuilder()
                .append(pad(mHour)).append(":")
                .append(pad(mMinute)));
    }

    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }

    // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

        public void onDateSet(DatePicker view, int year, 
                int monthOfYear, int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            displayDate();
        }
    };

    // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            mHour = hourOfDay;
            mMinute = minute;
            displayTime();
        }
    };

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this,
                    mDateSetListener,
                    mYear, mMonth, mDay);
        case TIME_DIALOG_ID:
            return new TimePickerDialog(this,
                    mTimeSetListener, mHour, mMinute, false);

        }
        return null;
    }   

}

18 comments :

  1. It is great you posted all this for us, although my MacBook Pro, Duo Core (2009 purchased)'s emulator really doesn't seem to operate it; fails to load or install actually... wondering if you might get it to work from a more standardized mode such as Android 2.2 or if there was some reason you used 12?? I'm green in terms of mobile device development. Thanks!

    ReplyDelete
  2. CalendarView is only available from API level 11. So other than that you can use the rest of the application such as DatePickerDialog and TimePickerDialog.
    You must comment out the code related to the CalendarView for it to work on android version 2.2

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete