Android Custom Date and Time Picker

Hi guys, i am back after a long break but IA, this time it will be continue for long time. because i have a lot of things to share on this blog.
Well straight to point:

Problem statement: Days back, when i was working on Smart Scheduler project, my PM wants me to add the widget to fetch the time and date from the same dialog. And genius "CommonsWare" said "There is nothing built into Android that offers this"But i got inspired from Runtastic "Jogging time" who created a dialog box with to pick height in cm and fit.inch.

Solutions:
Solution 1: Create a custom dialog with default date and time picker in vertical orientation but this solution might creates some problem in small screen size devices or alternatively you have to use the scroll bar that might suck the user interface.

Solution 2: Create a custom dialog with "ViewSwitcher" for date and time picker as shown in the image, there is a button to toggle the choose time and date.


Code Work:
Create a new project:
Project name:  AndroidCustomeDateTimePicker
Build Target:  Android 4.0.3 ( i will prefer)
Package name:  com.yo_android_yo.date_time_picker
Activity name: DateTimePickerActivity 

1. First of all we will create a custom relative layout file with the name of "DateTimePicker.java" and in this layout, we will implement the date and time picker with their respective listeners. Conversion from 24 hour format to 12 hour and vice verse, Similarly, the functionality of reset to current date option.
package com.yo_android_yo.date_time_picker;

import java.util.Calendar;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.ViewSwitcher;

import com.yo_android_yo.date_time_picker.R;

public class DateTimePicker extends RelativeLayout implements OnDateChangedListener, OnTimeChangedListener {

 private DatePicker datePicker;
 private TimePicker timePicker;
 static private ViewSwitcher viewSwitcher;
 private Calendar mCalendar;

 public DateTimePicker(Context context) {
  this(context, null);
 }

 public DateTimePicker(Context context, AttributeSet attrs) {
  this(context, attrs, 0);
 }

 public DateTimePicker(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);

  final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  inflater.inflate(R.layout.datetimepicker, this, true);

  final LinearLayout datePickerView = (LinearLayout) inflater.inflate(R.layout.datepicker, new LinearLayout(context));
  final LinearLayout timePickerView = (LinearLayout) inflater.inflate(R.layout.timepicker, new LinearLayout(context));

  mCalendar = Calendar.getInstance();
  viewSwitcher = (ViewSwitcher) this.findViewById(R.id.DateTimePickerVS);

  datePicker = (DatePicker) datePickerView.findViewById(R.id.DatePicker);
  datePicker.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), this);

  timePicker = (TimePicker) timePickerView.findViewById(R.id.TimePicker);
  timePicker.setOnTimeChangedListener(this);


  viewSwitcher.addView(datePickerView, 0);
  viewSwitcher.addView(timePickerView, 1);
 }

 public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
  mCalendar.set(year, monthOfYear, dayOfMonth, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE));
 }

 public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
  mCalendar.set(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), hourOfDay, minute);
 }

 void showDate() {
  viewSwitcher.showPrevious();
 }
 
 void showTime() {
  viewSwitcher.showNext();
 }

 public int get(final int field) {
  return mCalendar.get(field);
 }

 public void reset() {
  final Calendar c = Calendar.getInstance();
  updateDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
  updateTime(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE));
 }

 public long getDateTimeMillis() {
  return mCalendar.getTimeInMillis();
 }

 public void setIs24HourView(boolean is24HourView) {
  timePicker.setIs24HourView(is24HourView);
 }

 public boolean is24HourView() {
  return timePicker.is24HourView();
 }

 public void updateDate(int year, int monthOfYear, int dayOfMonth) {
  datePicker.updateDate(year, monthOfYear, dayOfMonth);
 }

 public void updateTime(int currentHour, int currentMinute) {
  timePicker.setCurrentHour(currentHour);
  timePicker.setCurrentMinute(currentMinute);
 }
}

1. Create a button in activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <Button
        android:id="@+id/ButtonDemo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Date and Time Picker" />

</RelativeLayout>
2. Create a dialog box on button click listener
3.  In this functional, we are creating a dialog box with custom UI with 3 buttons (Reset, pick date/pick time and Ok).
private void showDateTimeDialog() {
  final Dialog mDateTimeDialog = new Dialog(this);
  final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater().inflate(R.layout.date_time_dialog, null);
  final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);
//  final String timeS = android.provider.Settings.System.getString(getContentResolver(), android.provider.Settings.System.TIME_12_24);
//  final boolean is24h = !(timeS == null || timeS.equals("12"));
  final boolean is24h = false;
  ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime)).setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    mDateTimePicker.clearFocus();
    String time, date;
    date= mDateTimePicker.get(Calendar.YEAR) + "/" + (mDateTimePicker.get(Calendar.MONTH) + 1) + "/" + mDateTimePicker.get(Calendar.DAY_OF_MONTH);
    
    if (mDateTimePicker.is24HourView()) {
     time= mDateTimePicker.get(Calendar.HOUR_OF_DAY) + ":" + mDateTimePicker.get(Calendar.MINUTE);
    } else {
     time= mDateTimePicker.get(Calendar.HOUR) + ":" + mDateTimePicker.get(Calendar.MINUTE) + " " + (mDateTimePicker.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM");
    }
    
    Toast.makeText(DateTimePickerActivity.this, date+" "+time, Toast.LENGTH_LONG).show();
    mDateTimeDialog.dismiss();
   }
  });

  ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)).setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    String text = ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)).getText().toString();
    if (text.equals("Pick Time")) {
     mDateTimePicker.showTime();
     ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)).setText("Pick Date");
    } else if (text.equals("Pick Date")) {
     mDateTimePicker.showDate();
     ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)).setText("Pick Time");
    }
   }
  });

  ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime)).setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
    mDateTimePicker.reset();
   }
  });

  mDateTimePicker.setIs24HourView(is24h);
  mDateTimeDialog.setTitle("Date and Time Picker");
  mDateTimeDialog.setContentView(mDateTimeDialogView);
  mDateTimeDialog.show();
 }
The layout file for dialog box is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/DateTimeDialog"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <com.yo_android_yo.date_time_picker.DateTimePicker
        android:id="@+id/DateTimePicker"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:id="@+id/ControlButtons"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/DateTimePicker"
        android:background="#dddddd"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/ResetDateTime"
            style="@android:style/ButtonBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="1dp"
            android:layout_marginTop="1dp"
            android:layout_weight="1"
            android:background="@android:color/white"
            android:text="Reset" />

        <Button
            android:id="@+id/CancelDialog"
            style="@android:style/ButtonBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="1dp"
            android:layout_weight="1"
            android:background="@android:color/white"
            android:text="Pick Time" />

        <Button
            android:id="@+id/SetDateTime"
            style="@android:style/ButtonBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="1dp"
            android:layout_marginTop="1dp"
            android:layout_weight="1"
            android:background="@android:color/white"
            android:text="@android:string/ok" />
    </LinearLayout>

</RelativeLayout>

Android Custom Date and Time Picker Android Custom Date and Time Picker Reviewed by Unknown on Thursday, November 20, 2014 Rating: 5

1 comment:

attiqrao. Powered by Blogger.