从单个对话框片段中获取日期和时间选择器值,并在EditText中设置它

时间:2013-03-12 05:39:44

标签: android datepicker datetimepicker timepicker

我正在开发一个用户可以设置日期和时间的应用程序。我想在一个对话框片段中设置日期和时间,并将其设置为编辑文本。是否可以在1个对话框片段中使用日期和时间选择器?如果是的话,你是怎么做到的? 目前,我从对话框片段中获取时间,然后将其设置为EditText

我的代码是

LaterTextView=(TextView)findViewById(R.id.PickUp_later_TextView);



       LaterTextView.setOnClickListener(new View.OnClickListener() {

            @SuppressWarnings("deprecation")
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);

                }
        });




}


protected Dialog onCreateDialog(int id) {
    switch (id) {
    case TIME_DIALOG_ID:

        // set time picker as current time
        return new TimePickerDialog(this, timePickerListener, hour, minute,
                false);

    }
    return null;
}

private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
    public void onTimeSet(TimePicker view, int selectedHour,
            int selectedMinute) {
        hour = selectedHour;
        minute = selectedMinute;

        // set current time into TextView
        setDate_time_EditTExt.setText(new StringBuilder().append(pad(hour))
                .append(":").append(pad(minute)));



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

我想从同一个对话框片段中设置日期和时间。

3 个答案:

答案 0 :(得分:29)

单个对话框中

日期选择器时间选择器 。检查此代码。

<强> main_Activity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    custom = new CustomDateTimePicker(this,
            new CustomDateTimePicker.ICustomDateTimeListener() {

                @Override
                public void onSet(Dialog dialog, Calendar calendarSelected,
                        Date dateSelected, int year, String monthFullName,
                        String monthShortName, int monthNumber, int date,
                        String weekDayFullName, String weekDayShortName,
                        int hour24, int hour12, int min, int sec,
                        String AM_PM) {
                    ((TextView) findViewById(R.id.lablel))
                            .setText(calendarSelected
                                            .get(Calendar.DAY_OF_MONTH)
                                    + "/" + (monthNumber+1) + "/" + year
                                    + ", " + hour12 + ":" + min
                                    + " " + AM_PM);
                }

                @Override
                public void onCancel() {

                }
            });
    /**
     * Pass Directly current time format it will return AM and PM if you set
     * false
     */
    custom.set24HourFormat(false);
    /**
     * Pass Directly current data and time to show when it pop up
     */
    custom.setDate(Calendar.getInstance());

    findViewById(R.id.button_date).setOnClickListener(
            new OnClickListener() {

                @Override
                public void onClick(View v) {
                    custom.showDialog();
                }
            });
}

CustomDateTimePicker custom;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

<强> CustomDateTimePicker.java

public class CustomDateTimePicker implements OnClickListener {
private DatePicker datePicker;
private TimePicker timePicker;
private ViewSwitcher viewSwitcher;

private final int SET_DATE = 100, SET_TIME = 101, SET = 102, CANCEL = 103;

private Button btn_setDate, btn_setTime, btn_set, btn_cancel;

private Calendar calendar_date = null;

private Activity activity;

private ICustomDateTimeListener iCustomDateTimeListener = null;

private Dialog dialog;

private boolean is24HourView = true, isAutoDismiss = true;

private int selectedHour, selectedMinute;

public CustomDateTimePicker(Activity a,
        ICustomDateTimeListener customDateTimeListener) {
    activity = a;
    iCustomDateTimeListener = customDateTimeListener;

    dialog = new Dialog(activity);
    dialog.setOnDismissListener(new OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialog) {
            resetData();
        }
    });

    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    View dialogView = getDateTimePickerLayout();
    dialog.setContentView(dialogView);
}

public View getDateTimePickerLayout() {
    LinearLayout.LayoutParams linear_match_wrap = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    LinearLayout.LayoutParams linear_wrap_wrap = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    FrameLayout.LayoutParams frame_match_wrap = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.WRAP_CONTENT);

    LinearLayout.LayoutParams button_params = new LinearLayout.LayoutParams(
            0, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);

    LinearLayout linear_main = new LinearLayout(activity);
    linear_main.setLayoutParams(linear_match_wrap);
    linear_main.setOrientation(LinearLayout.VERTICAL);
    linear_main.setGravity(Gravity.CENTER);

    LinearLayout linear_child = new LinearLayout(activity);
    linear_child.setLayoutParams(linear_wrap_wrap);
    linear_child.setOrientation(LinearLayout.VERTICAL);

    LinearLayout linear_top = new LinearLayout(activity);
    linear_top.setLayoutParams(linear_match_wrap);

    btn_setDate = new Button(activity);
    btn_setDate.setLayoutParams(button_params);
    btn_setDate.setText("Set Date");
    btn_setDate.setId(SET_DATE);
    btn_setDate.setOnClickListener(this);

    btn_setTime = new Button(activity);
    btn_setTime.setLayoutParams(button_params);
    btn_setTime.setText("Set Time");
    btn_setTime.setId(SET_TIME);
    btn_setTime.setOnClickListener(this);

    linear_top.addView(btn_setDate);
    linear_top.addView(btn_setTime);

    viewSwitcher = new ViewSwitcher(activity);
    viewSwitcher.setLayoutParams(frame_match_wrap);

    datePicker = new DatePicker(activity);
    timePicker = new TimePicker(activity);
    timePicker.setOnTimeChangedListener(new OnTimeChangedListener() {
        @Override
        public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
            selectedHour = hourOfDay;
            selectedMinute = minute;
        }
    });

    viewSwitcher.addView(timePicker);
    viewSwitcher.addView(datePicker);

    LinearLayout linear_bottom = new LinearLayout(activity);
    linear_match_wrap.topMargin = 8;
    linear_bottom.setLayoutParams(linear_match_wrap);

    btn_set = new Button(activity);
    btn_set.setLayoutParams(button_params);
    btn_set.setText("Set");
    btn_set.setId(SET);
    btn_set.setOnClickListener(this);

    btn_cancel = new Button(activity);
    btn_cancel.setLayoutParams(button_params);
    btn_cancel.setText("Cancel");
    btn_cancel.setId(CANCEL);
    btn_cancel.setOnClickListener(this);

    linear_bottom.addView(btn_set);
    linear_bottom.addView(btn_cancel);

    linear_child.addView(linear_top);
    linear_child.addView(viewSwitcher);
    linear_child.addView(linear_bottom);

    linear_main.addView(linear_child);

    return linear_main;
}

public void showDialog() {
    if (!dialog.isShowing()) {
        if (calendar_date == null)
            calendar_date = Calendar.getInstance();

        selectedHour = calendar_date.get(Calendar.HOUR_OF_DAY);
        selectedMinute = calendar_date.get(Calendar.MINUTE);

        timePicker.setIs24HourView(is24HourView);
        timePicker.setCurrentHour(selectedHour);
        timePicker.setCurrentMinute(selectedMinute);

        datePicker.updateDate(calendar_date.get(Calendar.YEAR),
                calendar_date.get(Calendar.MONTH),
                calendar_date.get(Calendar.DATE));

        dialog.show();

        btn_setDate.performClick();
    }
}

public void setAutoDismiss(boolean isAutoDismiss) {
    this.isAutoDismiss = isAutoDismiss;
}

public void dismissDialog() {
    if (!dialog.isShowing())
        dialog.dismiss();
}

public void setDate(Calendar calendar) {
    if (calendar != null)
        calendar_date = calendar;
}

public void setDate(Date date) {
    if (date != null) {
        calendar_date = Calendar.getInstance();
        calendar_date.setTime(date);
    }
}

public void setDate(int year, int month, int day) {
    if (month < 12 && month >= 0 && day < 32 && day >= 0 && year > 100
            && year < 3000) {
        calendar_date = Calendar.getInstance();
        calendar_date.set(year, month, day);
    }

}

public void setTimeIn24HourFormat(int hourIn24Format, int minute) {
    if (hourIn24Format < 24 && hourIn24Format >= 0 && minute >= 0
            && minute < 60) {
        if (calendar_date == null)
            calendar_date = Calendar.getInstance();

        calendar_date.set(calendar_date.get(Calendar.YEAR),
                calendar_date.get(Calendar.MONTH),
                calendar_date.get(Calendar.DAY_OF_MONTH), hourIn24Format,
                minute);

        is24HourView = true;
    }
}

public void setTimeIn12HourFormat(int hourIn12Format, int minute,
        boolean isAM) {
    if (hourIn12Format < 13 && hourIn12Format > 0 && minute >= 0
            && minute < 60) {
        if (hourIn12Format == 12)
            hourIn12Format = 0;

        int hourIn24Format = hourIn12Format;

        if (!isAM)
            hourIn24Format += 12;

        if (calendar_date == null)
            calendar_date = Calendar.getInstance();

        calendar_date.set(calendar_date.get(Calendar.YEAR),
                calendar_date.get(Calendar.MONTH),
                calendar_date.get(Calendar.DAY_OF_MONTH), hourIn24Format,
                minute);

        is24HourView = false;
    }
}

public void set24HourFormat(boolean is24HourFormat) {
    is24HourView = is24HourFormat;
}

public interface ICustomDateTimeListener {
    public void onSet(Dialog dialog, Calendar calendarSelected,
            Date dateSelected, int year, String monthFullName,
            String monthShortName, int monthNumber, int date,
            String weekDayFullName, String weekDayShortName, int hour24,
            int hour12, int min, int sec, String AM_PM);

    public void onCancel();
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case SET_DATE:
        btn_setTime.setEnabled(true);
        btn_setDate.setEnabled(false);
        viewSwitcher.showNext();
        break;

    case SET_TIME:
        btn_setTime.setEnabled(false);
        btn_setDate.setEnabled(true);
        viewSwitcher.showPrevious();
        break;

    case SET:
        if (iCustomDateTimeListener != null) {
            int month = datePicker.getMonth();
            int year = datePicker.getYear();
            int day = datePicker.getDayOfMonth();


            calendar_date.set(year, month, day, selectedHour,
                    selectedMinute);

            iCustomDateTimeListener.onSet(dialog, calendar_date,
                    calendar_date.getTime(), calendar_date
                            .get(Calendar.YEAR),
                    getMonthFullName(calendar_date.get(Calendar.MONTH)),
                    getMonthShortName(calendar_date.get(Calendar.MONTH)),
                    calendar_date.get(Calendar.MONTH), calendar_date
                            .get(Calendar.DAY_OF_MONTH),
                    getWeekDayFullName(calendar_date
                            .get(Calendar.DAY_OF_WEEK)),
                    getWeekDayShortName(calendar_date
                            .get(Calendar.DAY_OF_WEEK)), calendar_date
                            .get(Calendar.HOUR_OF_DAY),
                    getHourIn12Format(calendar_date
                            .get(Calendar.HOUR_OF_DAY)), calendar_date
                            .get(Calendar.MINUTE), calendar_date
                            .get(Calendar.SECOND), getAMPM(calendar_date));
        }
        if (dialog.isShowing() && isAutoDismiss)
            dialog.dismiss();
        break;

    case CANCEL:
        if (iCustomDateTimeListener != null)
            iCustomDateTimeListener.onCancel();
        if (dialog.isShowing())
            dialog.dismiss();
        break;
    }
}

/**
 * @param date
 *            date in String
 * @param fromFormat
 *            format of your <b>date</b> eg: if your date is 2011-07-07
 *            09:09:09 then your format will be <b>yyyy-MM-dd hh:mm:ss</b>
 * @param toFormat
 *            format to which you want to convert your <b>date</b> eg: if
 *            required format is 31 July 2011 then the toFormat should be
 *            <b>d MMMM yyyy</b>
 * @return formatted date
 */
public static String convertDate(String date, String fromFormat,
        String toFormat) {
    try {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(fromFormat);
        Date d = simpleDateFormat.parse(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);

        simpleDateFormat = new SimpleDateFormat(toFormat);
        simpleDateFormat.setCalendar(calendar);
        date = simpleDateFormat.format(calendar.getTime());

    } catch (Exception e) {
        e.printStackTrace();
    }

    return date;
}

private String getMonthFullName(int monthNumber) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.MONTH, monthNumber);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM");
    simpleDateFormat.setCalendar(calendar);
    String monthName = simpleDateFormat.format(calendar.getTime());

    return monthName;
}

private String getMonthShortName(int monthNumber) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.MONTH, monthNumber);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM");
    simpleDateFormat.setCalendar(calendar);
    String monthName = simpleDateFormat.format(calendar.getTime());

    return monthName;
}

private String getWeekDayFullName(int weekDayNumber) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.DAY_OF_WEEK, weekDayNumber);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
    simpleDateFormat.setCalendar(calendar);
    String weekName = simpleDateFormat.format(calendar.getTime());

    return weekName;
}

private String getWeekDayShortName(int weekDayNumber) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.DAY_OF_WEEK, weekDayNumber);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EE");
    simpleDateFormat.setCalendar(calendar);
    String weekName = simpleDateFormat.format(calendar.getTime());

    return weekName;
}

private int getHourIn12Format(int hour24) {
    int hourIn12Format = 0;

    if (hour24 == 0)
        hourIn12Format = 12;
    else if (hour24 <= 12)
        hourIn12Format = hour24;
    else
        hourIn12Format = hour24 - 12;

    return hourIn12Format;
}

private String getAMPM(Calendar calendar) {
    String ampm = (calendar.get(Calendar.AM_PM) == (Calendar.AM)) ? "AM"
            : "PM";
    return ampm;
}

private void resetData() {
    calendar_date = null;
    is24HourView = true;
}

public static String pad(int integerToPad) {
    if (integerToPad >= 10 || integerToPad < 0)
        return String.valueOf(integerToPad);
    else
        return "0" + String.valueOf(integerToPad);
}
}

<强> 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" >

<TextView
    android:id="@+id/lablel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:padding="@dimen/padding_medium"
    android:text="@string/hello_world"
    android:textColor="#000"
    android:textSize="20dp"
    tools:context=".MainActivity" />

<Button
    android:id="@+id/button_date"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/lablel"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="80dp"
    android:text="Date Time Picker" />

</RelativeLayout>

enter image description here

答案 1 :(得分:4)

这很简单:

您必须在Bundle对象中设置对话框的日期/时间,并使用消息的Message方法在setData对象中设置该Bundle,然后在要检索这些日期的活动中你必须做的时间价值

以下是我如何做到这一点:

public class DatePickerDialog extends DialogFragment {
    private Handler dialogPickerHandler;
    private int mYear;
    private int mMonth;
    private int mDay;   
    private Bundle mBundle;

    /** This is the one argument constructor */
    public DatePickerDialog(Handler h) {
        /**
         * Getting the reference to the message handler instance instantiated in
         * calling activity
         */

        dialogPickerHandler = h;
    } // end constructor

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        mBundle = getArguments();

        mYear = mBundle.getInt("set_year");
        mDay = mBundle.getInt("set_day");
        mMonth = mBundle.getInt("set_month");

        return new android.app.DatePickerDialog(getActivity(),
                mDateSetListener, mYear, mMonth, mDay);
    }

    private OnDateSetListener mDateSetListener = new OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {

            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;

            Bundle b = new Bundle();

            b.putInt("set_year", mYear);
            b.putInt("set_month", mMonth);
            b.putInt("set_day", mDay);

            Message m = new Message();

            m.setData(b);

            dialogPickerHandler.sendMessage(m);

        }
    };

}

在要检索这些值的活动中,您必须执行以下操作:

 private Bundle mBundle;
    private int mtYear;
    private int mDay;
    private int mMonth;
    private Calendar your_date_object;
    private EditText your_edit_text;
    private SimpleDateFormat simpleDateFormat

    Handler mHandler = new Handler() {
        public void handleMessage(Message m) {
            mBundle = m.getData();

            mtYear = mBundle.getInt("set_year");
            mDay = mBundle.getInt("set_day");
            mMonth = mBundle.getInt("set_month");


            /** update the time on the start Date Button */
            your_date_object.set(mtYear, mMonth, mDay);

            your_edit_text.setText(simpleDateFormat.format(startDate
                        .getTime()));


        }
    };

确保您在活动的simpleDateFormat方法中初始化your_date_objectonCreate,如下所示:

/** Initialize the simpleDateFormat object */
    simpleDateFormat = new SimpleDateFormat("yyyy dd, MM");

    /** Initialize the your_date_object */

    your_date_object = new GregorianCalendar();

多数民众赞成。 :)

答案 2 :(得分:0)

首先感谢@Mr。沙 编辑@Mr。 Sandy Code应该给予应有的尊重,以增加一些额外的功能。

  • 过去没有日期
  • 错误消息
  • 以毫秒为单位的时间

<强> Main_Activity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    custom = new CustomDateTimePicker(this,
            new CustomDateTimePicker.ICustomDateTimeListener() {

                @Override
                public void onSet(Dialog dialog, Calendar calendarSelected,
                        Date dateSelected, int year, String monthFullName,
                        String monthShortName, int monthNumber, int date,
                        String weekDayFullName, String weekDayShortName,
                        int hour24, int hour12, int min, int sec,
                        String AM_PM, long _timeInMillies) {
                    ((TextView) findViewById(R.id.lablel))
                            .setText(calendarSelected
                                            .get(Calendar.DAY_OF_MONTH)
                                    + "/" + (monthNumber+1) + "/" + year
                                    + ", " + hour12 + ":" + min
                                    + " " + AM_PM);
long timeInMillies = _timeInMillies;

                }

                @Override
                public void onCancel() {

                }
            });
    /**
     * Pass Directly current time format it will return AM and PM if you set
     * false
     */
    custom.set24HourFormat(false);
    /**
     * Pass Directly current data and time to show when it pop up
     */
    custom.setDate(Calendar.getInstance());

    findViewById(R.id.button_date).setOnClickListener(
            new OnClickListener() {

                @Override
                public void onClick(View v) {
                    custom.showDialog();
                }
            });
}

CustomDateTimePicker custom;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

<强> CustomDateTimePicker.java

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Typeface;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.Toast;
import android.widget.ViewSwitcher;


public class CustomDateTimePicker implements OnClickListener {
    private DatePicker datePicker;
    private TimePicker timePicker;
    private ViewSwitcher viewSwitcher;

    private final int SET_DATE = 100, SET_TIME = 101, SET = 102, CANCEL = 103;

    private Button btn_setDate, btn_setTime, btn_set, btn_cancel;

    private TextView errMsg;

    private Calendar calendar_date = null;

    private Activity activity;

    private ICustomDateTimeListener iCustomDateTimeListener = null;

    private Dialog dialog;

    private boolean is24HourView = true, isAutoDismiss = true;

    private int selectedHour, selectedMinute;

    public CustomDateTimePicker(Activity a,
            ICustomDateTimeListener customDateTimeListener) {
        activity = a;
        iCustomDateTimeListener = customDateTimeListener;

        dialog = new Dialog(activity);
        dialog.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                resetData();

            }
        });
        dialog.setCancelable(false);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View dialogView = getDateTimePickerLayout();
        dialog.setContentView(dialogView);
    }

    public View getDateTimePickerLayout() {


        LinearLayout.LayoutParams linear_match_wrap = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        LinearLayout.LayoutParams linear_wrap_wrap = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        FrameLayout.LayoutParams frame_match_wrap = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.WRAP_CONTENT);

        LinearLayout.LayoutParams button_params = new LinearLayout.LayoutParams(
                0, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);

        LinearLayout linear_main = new LinearLayout(activity);
        linear_main.setLayoutParams(linear_match_wrap);
        linear_main.setOrientation(LinearLayout.VERTICAL);
        linear_main.setGravity(Gravity.CENTER);

        LinearLayout linear_child = new LinearLayout(activity);
        linear_child.setLayoutParams(linear_wrap_wrap);
        linear_child.setOrientation(LinearLayout.VERTICAL);

        LinearLayout linear_top = new LinearLayout(activity);
        linear_top.setLayoutParams(linear_match_wrap);

        btn_setDate = new Button(activity);
        btn_setDate.setLayoutParams(button_params);
        btn_setDate.setText("Set Date");
        btn_setDate.setId(SET_DATE);
        btn_setDate.setOnClickListener(this);

        btn_setTime = new Button(activity);
        btn_setTime.setLayoutParams(button_params);
        btn_setTime.setText("Set Time");
        btn_setTime.setId(SET_TIME);
        btn_setTime.setOnClickListener(this);

        linear_top.addView(btn_setDate);
        linear_top.addView(btn_setTime);

        viewSwitcher = new ViewSwitcher(activity);
        viewSwitcher.setLayoutParams(frame_match_wrap);

        datePicker = new DatePicker(activity);
        timePicker = new TimePicker(activity);
        timePicker.setOnTimeChangedListener(new OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                selectedHour = hourOfDay;
                selectedMinute = minute;
            }
        });

        viewSwitcher.addView(timePicker);
        viewSwitcher.addView(datePicker);

        LinearLayout linear_bottom = new LinearLayout(activity);
        linear_match_wrap.topMargin = 8;
        linear_bottom.setLayoutParams(linear_match_wrap);

        btn_set = new Button(activity);
        btn_set.setLayoutParams(button_params);
        btn_set.setText("Set");
        btn_set.setId(SET);
        btn_set.setOnClickListener(this);

        btn_cancel = new Button(activity);
        btn_cancel.setLayoutParams(button_params);
        btn_cancel.setText("Cancel");
        btn_cancel.setId(CANCEL);
        btn_cancel.setOnClickListener(this);

        linear_bottom.addView(btn_set);
        linear_bottom.addView(btn_cancel);

        errMsg = new TextView(activity);
        errMsg.setLayoutParams(linear_match_wrap);
        errMsg.setText("Can't Select Date From Past.");
        errMsg.setTextColor(activity.getResources().getColor(R.color.Red));
        errMsg.setGravity(Gravity.CENTER_HORIZONTAL);
        errMsg.setTypeface(face);
        errMsg.setVisibility(View.GONE);

        linear_child.addView(linear_top);
        linear_child.addView(viewSwitcher);
        linear_child.addView(errMsg);
        linear_child.addView(linear_bottom);

        linear_main.addView(linear_child);

        return linear_main;
    }

    public void showDialog() {
        if (!dialog.isShowing()) {
            if (calendar_date == null)
                calendar_date = Calendar.getInstance();

            selectedHour = calendar_date.get(Calendar.HOUR_OF_DAY);
            selectedMinute = calendar_date.get(Calendar.MINUTE);

            timePicker.setIs24HourView(is24HourView);
            timePicker.setCurrentHour(selectedHour);
            timePicker.setCurrentMinute(selectedMinute);

            datePicker.updateDate(calendar_date.get(Calendar.YEAR),
                    calendar_date.get(Calendar.MONTH),
                    calendar_date.get(Calendar.DATE));

            dialog.show();

            btn_setDate.performClick();
        }
    }

    public void setAutoDismiss(boolean isAutoDismiss) {
        this.isAutoDismiss = isAutoDismiss;
    }

    public void dismissDialog() {
        if (!dialog.isShowing())
            dialog.dismiss();
    }

    public void setDate(Calendar calendar) {
        if (calendar != null)
            calendar_date = calendar;
    }

    public void setDate(Date date) {
        if (date != null) {
            calendar_date = Calendar.getInstance();
            calendar_date.setTime(date);
        }
    }

    public void setDate(int year, int month, int day) {
        if (month < 12 && month >= 0 && day < 32 && day >= 0 && year > 100
                && year < 3000) {
            calendar_date = Calendar.getInstance();
            calendar_date.set(year, month, day);
        }

    }

    public void setTimeIn24HourFormat(int hourIn24Format, int minute) {
        if (hourIn24Format < 24 && hourIn24Format >= 0 && minute >= 0
                && minute < 60) {
            if (calendar_date == null)
                calendar_date = Calendar.getInstance();

            calendar_date.set(calendar_date.get(Calendar.YEAR),
                    calendar_date.get(Calendar.MONTH),
                    calendar_date.get(Calendar.DAY_OF_MONTH), hourIn24Format,
                    minute);

            is24HourView = true;
        }
    }

    public void setTimeIn12HourFormat(int hourIn12Format, int minute,
            boolean isAM) {
        if (hourIn12Format < 13 && hourIn12Format > 0 && minute >= 0
                && minute < 60) {
            if (hourIn12Format == 12)
                hourIn12Format = 0;

            int hourIn24Format = hourIn12Format;

            if (!isAM)
                hourIn24Format += 12;

            if (calendar_date == null)
                calendar_date = Calendar.getInstance();

            calendar_date.set(calendar_date.get(Calendar.YEAR),
                    calendar_date.get(Calendar.MONTH),
                    calendar_date.get(Calendar.DAY_OF_MONTH), hourIn24Format,
                    minute);

            is24HourView = false;
        }
    }

    public void set24HourFormat(boolean is24HourFormat) {
        is24HourView = is24HourFormat;
    }

    public interface ICustomDateTimeListener {
        public void onSet(Dialog dialog, Calendar calendarSelected,
                Date dateSelected, int year, String monthFullName,
                String monthShortName, int monthNumber, int date,
                String weekDayFullName, String weekDayShortName, int hour24,
                int hour12, int min, int sec, String AM_PM, long timeinMilliSec);

        public void onCancel();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case SET_DATE:
            btn_setTime.setEnabled(true);
            btn_setDate.setEnabled(false);
            viewSwitcher.showNext();
            break;

        case SET_TIME:
            btn_setTime.setEnabled(false);
            btn_setDate.setEnabled(true);
            viewSwitcher.showPrevious();
            break;

        case SET:
            if (iCustomDateTimeListener != null) {
                int month = datePicker.getMonth();
                int year = datePicker.getYear();
                int day = datePicker.getDayOfMonth();

                Calendar cal = Calendar.getInstance();
                Log.i("Date",
                        " " + cal.get(Calendar.YEAR) + " "
                                + datePicker.getYear() + " Month"
                                + cal.get(Calendar.MONTH) + " "
                                + datePicker.getMonth() + "Date "
                                + cal.get(Calendar.DAY_OF_MONTH) + " "
                                + datePicker.getDayOfMonth());
                if (cal.get(Calendar.YEAR) <= datePicker.getYear()
                        && cal.get(Calendar.MONTH) <= datePicker.getMonth()
                        && cal.get(Calendar.DAY_OF_MONTH) <= datePicker
                                .getDayOfMonth()) {
                    calendar_date.set(year, month, day, selectedHour,
                            selectedMinute);

                    iCustomDateTimeListener
                            .onSet(dialog, calendar_date, calendar_date
                                    .getTime(), calendar_date
                                    .get(Calendar.YEAR),
                                    getMonthFullName(calendar_date
                                            .get(Calendar.MONTH)),
                                    getMonthShortName(calendar_date
                                            .get(Calendar.MONTH)),
                                    calendar_date.get(Calendar.MONTH),
                                    calendar_date.get(Calendar.DAY_OF_MONTH),
                                    getWeekDayFullName(calendar_date
                                            .get(Calendar.DAY_OF_WEEK)),
                                    getWeekDayShortName(calendar_date
                                            .get(Calendar.DAY_OF_WEEK)),
                                    calendar_date.get(Calendar.HOUR_OF_DAY),
                                    getHourIn12Format(calendar_date
                                            .get(Calendar.HOUR_OF_DAY)),
                                    calendar_date.get(Calendar.MINUTE),
                                    calendar_date.get(Calendar.SECOND),
                                    getAMPM(calendar_date),calendar_date.getTimeInMillis());

                    if (dialog.isShowing() && isAutoDismiss)
                        dialog.dismiss();
                } else {
                    errMsg.setVisibility(View.VISIBLE);
                }
            }
            break;

        case CANCEL:
            if (iCustomDateTimeListener != null)
                iCustomDateTimeListener.onCancel();
            if (dialog.isShowing())
                dialog.dismiss();
            break;
        }
    }

    /**
     * @param date
     *            date in String
     * @param fromFormat
     *            format of your <b>date</b> eg: if your date is 2011-07-07
     *            09:09:09 then your format will be <b>yyyy-MM-dd hh:mm:ss</b>
     * @param toFormat
     *            format to which you want to convert your <b>date</b> eg: if
     *            required format is 31 July 2011 then the toFormat should be
     *            <b>d MMMM yyyy</b>
     * @return formatted date
     */
    public static String convertDate(String date, String fromFormat,
            String toFormat) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(fromFormat);
            Date d = simpleDateFormat.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(d);

            simpleDateFormat = new SimpleDateFormat(toFormat);
            simpleDateFormat.setCalendar(calendar);
            date = simpleDateFormat.format(calendar.getTime());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return date;
    }

    private String getMonthFullName(int monthNumber) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, monthNumber);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM");
        simpleDateFormat.setCalendar(calendar);
        String monthName = simpleDateFormat.format(calendar.getTime());

        return monthName;
    }

    private String getMonthShortName(int monthNumber) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, monthNumber);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM");
        simpleDateFormat.setCalendar(calendar);
        String monthName = simpleDateFormat.format(calendar.getTime());

        return monthName;
    }

    private String getWeekDayFullName(int weekDayNumber) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, weekDayNumber);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
        simpleDateFormat.setCalendar(calendar);
        String weekName = simpleDateFormat.format(calendar.getTime());

        return weekName;
    }

    private String getWeekDayShortName(int weekDayNumber) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, weekDayNumber);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EE");
        simpleDateFormat.setCalendar(calendar);
        String weekName = simpleDateFormat.format(calendar.getTime());

        return weekName;
    }

    private int getHourIn12Format(int hour24) {
        int hourIn12Format = 0;

        if (hour24 == 0)
            hourIn12Format = 12;
        else if (hour24 <= 12)
            hourIn12Format = hour24;
        else
            hourIn12Format = hour24 - 12;

        return hourIn12Format;
    }

    private String getAMPM(Calendar calendar) {
        String ampm = (calendar.get(Calendar.AM_PM) == (Calendar.AM)) ? "AM"
                : "PM";
        return ampm;
    }

    private void resetData() {
        calendar_date = null;
        is24HourView = true;
    }

    public static String pad(int integerToPad) {
        if (integerToPad >= 10 || integerToPad < 0)
            return String.valueOf(integerToPad);
        else
            return "0" + String.valueOf(integerToPad);
    }
}