web-dev-qa-db-fra.com

Android Date Time sélecteur dans une boîte de dialogue

J'utilise le matériel DateTime picker pour mon application Android. Mais je veux combiner les sélecteurs Date et Time dans une boîte de dialogue.

Je suis celui-ci . Mais je dois sélectionner l'heure juste après la sélection de la date.

S'il vous plaît suggérer un moyen possible de faire celui-ci.

13
anuradha

Vous pouvez appeler TimePicker après DatePicker set Date. Comme ça..

    String date_time = "";
    int mYear;
    int mMonth;
    int mDay;

    int mHour;
    int mMinute;

    et_show_date_time = (EditText) findViewById(R.id.et_show_date_time);
    btn_set_date_time = (Button) findViewById(R.id.btn_set_date_time);

    btn_set_date_time.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            datePicker();

        }
    });

Sélecteur de date:

    private void datePicker(){

    // Get Current Date
    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

    DatePickerDialog datePickerDialog = new DatePickerDialog(this,
            new DatePickerDialog.OnDateSetListener() {

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

                    date_time = dayOfMonth + "-" + (monthOfYear + 1) + "-" + year;
                   //*************Call Time Picker Here ********************
                   tiemPicker();
                }
            }, mYear, mMonth, mDay);
       datePickerDialog.show();
    }

Sélecteur de temps

 private void tiemPicker(){
    // Get Current Time
    final Calendar c = Calendar.getInstance();
    mHour = c.get(Calendar.HOUR_OF_DAY);
    mMinute = c.get(Calendar.MINUTE);

    // Launch Time Picker Dialog
    TimePickerDialog timePickerDialog = new TimePickerDialog(this,
            new TimePickerDialog.OnTimeSetListener() {

                @Override
                public void onTimeSet(TimePicker view, int hourOfDay,int minute) {

                    mHour = hourOfDay;
                    mMinute = minute;

                    et_show_date_time.setText(date_time+" "+hourOfDay + ":" + minute);
                }
            }, mHour, mMinute, false);
    timePickerDialog.show();
}

-

31
user4696837

Essayez ce code: 

CustomDateTimePicker.Java

import Android.app.Activity;
import Android.app.Dialog;
import Android.content.DialogInterface;
import Android.view.Gravity;
import Android.view.View;
import Android.view.Window;
import Android.widget.Button;
import Android.widget.DatePicker;
import Android.widget.FrameLayout;
import Android.widget.LinearLayout;
import Android.widget.TimePicker;
import Android.widget.ViewSwitcher;

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

/**
 * Created by admin on 6/29/2016.
 */
public class CustomDateTimePicker implements View.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 DialogInterface.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 TimePicker.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);

            if (viewSwitcher.getCurrentView() != datePicker) {
                viewSwitcher.showPrevious();
            }
            break;

        case SET_TIME:
            btn_setTime.setEnabled(false);
            btn_setDate.setEnabled(true);
            if (viewSwitcher.getCurrentView() == datePicker) {
                viewSwitcher.showNext();
            }
            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);
    }
}

Dans votre activité: 

MainActivity.Java: 

    public class MainActivity extends Activity{

     CustomDateTimePicker custom;
Button btnEventDateTime;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    btnEventDateTime = ((Button) findViewById(R.id.btnEventDateTime));
    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) {
    //                        ((TextInputEditText) findViewById(R.id.edtEventDateTime))
                            edtEventDateTime.setText("");
                            edtEventDateTime.setText(year
                                    + "-" + (monthNumber + 1) + "-" + calendarSelected.get(Calendar.DAY_OF_MONTH)
                                    + " " + hour24 + ":" + min
                                    + ":" + sec);
                        }

                        @Override
                        public void onCancel() {

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

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

Si vous devez sélectionner l'heure juste après la sélection de la date, vous pouvez simplement afficher TimePickerDialog automatiquement après la date sélectionnée. C'est le moyen le plus simple.

Si vous avez un auditeur activé lorsque la date est sélectionnée avec la date sélectionnée, vous pouvez simplement passer cette date à TimePickerDialog et avec quelques personnalisations dans mdtp_time_picker_dialog.xml, vous pouvez ajouter une TextView pour afficher le texte sélectionné.

Une autre option est de fusionner mdtp_time_picker_dialog.xml et mdtp_date_picker_dialog.xml qui sont des modèles racine pour les boîtes de dialogue du sélecteur de date et de sélection de l'heure. Vous pouvez définir la visibilité des pièces du sélecteur de temps sur GONE et changer la visibilité lorsque vous souhaitez changer de sélecteur.

La deuxième solution est plus difficile à mettre en œuvre car en plus des dispositions, vous devez fusionner tous les contrôles et les écouteurs.

Si vous voulez que l'utilisateur voie les deux sélecteurs, je pense que vous devez réellement concevoir une nouvelle vue vous-même. Cette disposition de la bibliothèque ne convient pas pour cela.

1
Misagh Emamverdi

Utilisez ce code simple .. J'utilise ce code dans mon projet ..

final Calendar currentDate = Calendar.getInstance();
date = Calendar.getInstance();
            DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {

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

                    date.set(year, monthOfYear, dayOfMonth);
                    new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                            date.set(Calendar.HOUR_OF_DAY, hourOfDay);
                            date.set(Calendar.MINUTE, minute);
                            // Log.v(TAG, "The choosen one " + date.getTime());
                            // Toast.makeText(getContext(),"The choosen one " + date.getTime(),Toast.LENGTH_SHORT).show();
                            datetime.setText(new SimpleDateFormat("dd-MMM-yyyy h:mm a").format(date.getTime()));
                        }
                    },currentDate.get(Calendar.HOUR_OF_DAY), currentDate.get(Calendar.MINUTE), false).show();

                }
            }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE));
            datePickerDialog.getDatePicker().setMinDate(currentDate.getTimeInMillis());
            datePickerDialog.show();
0
Rajesh Naddy

Cette réponse est essentiellement une amélioration de la réponse donnée par @Mayur Patel: https://stackoverflow.com/a/38604615/3994127

CustomDateTimePicker.Java

import Android.app.Dialog;
import Android.content.Context;
import Android.content.DialogInterface;
import Android.support.v7.widget.AppCompatButton;
import Android.view.View;
import Android.view.Window;
import Android.widget.DatePicker;
import Android.widget.TimePicker;
import Android.widget.ViewSwitcher;

import com.gotrack.gotrack.R;

import Java.text.SimpleDateFormat;
import Java.util.Calendar;
import Java.util.Date;
import Java.util.Locale;

public class CustomDateTimePicker implements View.OnClickListener {
    private Calendar calendar_date = null;
    private ViewSwitcher viewSwitcher;
    private DatePicker datePicker;
    private TimePicker timePicker;
    private AppCompatButton btnDate, btnTime;

    private ICustomDateTimeListener iCustomDateTimeListener = null;

    private Dialog dialog;

    private boolean is24HourView = true, isAutoDismiss = true;

    private int selectedHour, selectedMinute;

    public CustomDateTimePicker(Context context,
                                ICustomDateTimeListener customDateTimeListener) {
        iCustomDateTimeListener = customDateTimeListener;

        dialog = new Dialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.date_time_picker);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                resetData();
            }
        });
    }

    private void setView() {
        btnDate = dialog.findViewById(R.id.btn_date);
        btnTime = dialog.findViewById(R.id.btn_time);
        dialog.findViewById(R.id.btn_set).setOnClickListener(this);
        dialog.findViewById(R.id.btn_cancel).setOnClickListener(this);
        viewSwitcher = dialog.findViewById(R.id.view_switcher);
        datePicker = dialog.findViewById(R.id.date_picker);
        timePicker = dialog.findViewById(R.id.time_picker);

        btnDate.setOnClickListener(this);
        btnTime.setOnClickListener(this);

        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));

        btnDate.performClick();
    }

    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);

            dialog.show();

            setView();
        }
    }

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

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

        return this;
    }

    public CustomDateTimePicker setDate(Calendar calendar) {
        if (calendar != null)
            calendar_date = calendar;
        return this;
    }

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

    public CustomDateTimePicker 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);
        }
        return this;
    }

    public CustomDateTimePicker 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;
        }
        return this;
    }

    public CustomDateTimePicker 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;
        }
        return this;
    }

    public CustomDateTimePicker set24HourFormat(boolean is24HourFormat) {
        is24HourView = is24HourFormat;
        return this;
    }

    public interface ICustomDateTimeListener {
        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);

        void onCancel();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_date:
                btnTime.setEnabled(true);
                btnDate.setEnabled(false);

                if (viewSwitcher.getCurrentView() != datePicker) {
                    viewSwitcher.showPrevious();
                }
                break;

            case R.id.btn_time:
                btnTime.setEnabled(false);
                btnDate.setEnabled(true);
                if (viewSwitcher.getCurrentView() == datePicker) {
                    viewSwitcher.showNext();
                }
                break;


            case R.id.btn_set:
                if (iCustomDateTimeListener != null) {
                    int month = datePicker.getMonth();
                    int year = datePicker.getYear();
                    int day = datePicker.getDayOfMonth();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    selectedHour = timePicker.getHour();
                    selectedMinute = timePicker.getMinute();
                } else {
                    selectedHour = timePicker.getCurrentHour();
                    selectedMinute = timePicker.getCurrentMinute();
                }

                    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 R.id.btn_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, Locale.getDefault());
            Date d = simpleDateFormat.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(d);

            simpleDateFormat = new SimpleDateFormat(toFormat, Locale.getDefault());
            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", Locale.getDefault());
        simpleDateFormat.setCalendar(calendar);

        return simpleDateFormat.format(calendar.getTime());
    }

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

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM", Locale.getDefault());
        simpleDateFormat.setCalendar(calendar);

        return simpleDateFormat.format(calendar.getTime());
    }

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

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE", Locale.getDefault());
        simpleDateFormat.setCalendar(calendar);

        return simpleDateFormat.format(calendar.getTime());
    }

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

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EE", Locale.getDefault());
        simpleDateFormat.setCalendar(calendar);

        return simpleDateFormat.format(calendar.getTime());
    }

    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) {
        return (calendar.get(Calendar.AM_PM) == (Calendar.AM)) ? "AM"
                : "PM";
    }

    private CustomDateTimePicker resetData() {
        calendar_date = null;
        is24HourView = true;
        return this;
    }

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

date_time_picker.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:app="http://schemas.Android.com/apk/res-auto"
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content">

    <Android.support.constraint.ConstraintLayout
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:padding="15dp">

        <Android.support.v7.widget.AppCompatButton
            Android:id="@+id/btn_date"
            Android:layout_width="0dp"
            Android:layout_height="wrap_content"
            Android:layout_marginEnd="5dp"
            Android:text="@string/set_date"
            app:backgroundTint="@color/colorPrimary"
            app:layout_constraintEnd_toStartOf="@+id/btn_time"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <Android.support.v7.widget.AppCompatButton
            Android:id="@+id/btn_time"
            Android:layout_width="0dp"
            Android:layout_height="wrap_content"
            Android:layout_marginStart="5dp"
            Android:text="@string/set_time"
            app:backgroundTint="@color/colorPrimary"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/btn_date"
            app:layout_constraintTop_toTopOf="parent" />

        <Android.support.v7.widget.AppCompatButton
            Android:id="@+id/btn_set"
            Android:layout_width="0dp"
            Android:layout_height="wrap_content"
            Android:layout_marginEnd="5dp"
            Android:text="@string/set"
            app:backgroundTint="@color/colorPrimary"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/btn_cancel"
            app:layout_constraintStart_toStartOf="parent" />

        <Android.support.v7.widget.AppCompatButton
            Android:id="@+id/btn_cancel"
            Android:layout_width="0dp"
            Android:layout_height="wrap_content"
            Android:layout_marginStart="5dp"
            Android:text="@string/cancel"
            app:backgroundTint="@color/colorPrimary"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/btn_set" />

        <ViewSwitcher
            Android:id="@+id/view_switcher"
            Android:layout_width="0dp"
            Android:layout_height="wrap_content"
            app:layout_constraintBottom_toTopOf="@+id/btn_set"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/btn_date">

            <DatePicker
                Android:id="@+id/date_picker"
                Android:layout_width="match_parent"
                Android:layout_height="wrap_content"
                Android:layout_gravity="center"
                Android:theme="@style/DialogTheme" />

            <TimePicker
                Android:id="@+id/time_picker"
                Android:layout_width="match_parent"
                Android:layout_height="wrap_content"
                Android:layout_gravity="center"
                Android:theme="@style/DialogTheme" />
        </ViewSwitcher>
    </Android.support.constraint.ConstraintLayout>
</RelativeLayout>

Style DialogTheme

<style name="DialogTheme">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
</style>

Code d'appel

new CustomDateTimePicker(context,
        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) {

            }

            @Override
            public void onCancel() {

            }
        }).set24HourFormat(true).setDate(Calendar.getInstance())
        .showDialog();
0
Raghav Satyadev

Googlé ce problème et trouvé utile réponse Enamul Haque. Modifié son code un peu et obtenu ce résultat. Sa solution rapide et sera améliorée, mais fonctionne bien)

public class DateTimePicker {

    @NonNull
    private final Calendar calendar = Calendar.getInstance();
    @Nullable
    private DatePickerDialog datePickerDialog;
    @Nullable
    private TimePickerDialog timePickerDialog;
    @Nullable
    private ResultCallback<Date> dateResultCallback;

    public void showDialog(@NonNull Context context, long time) {
        calendar.setTimeInMillis(time);
        closeDialogs();
        showDatePicker(context);
    }

    @Nullable
    public ResultCallback<Date> getDateResultCallback() {
        return dateResultCallback;
    }

    public void setDateResultCallback(@Nullable ResultCallback<Date> dateResultCallback) {
        this.dateResultCallback = dateResultCallback;
    }

    public long getTime() {
        return calendar.getTimeInMillis();
    }

    private void closeDialogs() {
        if (datePickerDialog != null) {
            datePickerDialog.dismiss();
            datePickerDialog = null;
        }
        if (timePickerDialog != null) {
            timePickerDialog.dismiss();
            timePickerDialog = null;
        }
    }

    private DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            timePicker(view.getContext());
        }
    };

    private TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            calendar.set(Calendar.MINUTE, minute);
            if (dateResultCallback != null) {
                dateResultCallback.onResult(calendar.getTime());
            }
        }
    };

    private void showDatePicker(@NonNull Context context) {
        datePickerDialog = new DatePickerDialog(context,
                dateSetListener,
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }

    private void timePicker(@NonNull Context context) {
        timePickerDialog = new TimePickerDialog(context,
                timeSetListener,
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                true);
        timePickerDialog.show();
    }

    public void release() {
        closeDialogs();
        dateResultCallback = null;
    }

}

Appels de dialogue via la méthode showDialog (...), possible de libérer un objet quand il n'en a plus besoin (in onDestroy () dans l'activité f.e). .__ Et encore - merci à Enamul Haque pour son idée.

0
Ruslan Podurets