Skip to content

Instantly share code, notes, and snippets.

@studiofuga
Last active August 29, 2015 14:25
Show Gist options
  • Save studiofuga/496d7ff7f8647115ec08 to your computer and use it in GitHub Desktop.
Save studiofuga/496d7ff7f8647115ec08 to your computer and use it in GitHub Desktop.
DateTimePicker Dialog
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:padding="8dp"
android:layout_height="match_parent">
<DatePicker
android:id="@+id/date_picker"
android:layout_width="match_parent"
android:calendarViewShown="true"
android:spinnersShown="false"
<!-- These will show spinners instead of calendar
android:calendarViewShown="false"
android:datePickerMode="spinner"
-->
android:layout_weight="4"
android:layout_height="0dp" />
<TimePicker
android:id="@+id/time_picker"
android:layout_weight="4"
android:layout_width="match_parent"
<!-- This will show a spinner
android:timePickerMode="spinner"
-->
android:layout_height="0dp" />
<Button
android:id="@+id/date_time_set"
android:layout_weight="1"
android:layout_width="match_parent"
android:text="Set"
android:layout_height="0dp" />
</LinearLayout>
private void shodDateDialog() {
final View dialogView = View.inflate(this, R.layout.date_time_picker, null);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
/* This will set up the default values */
Calendar calendar = Calendar.getInstance();
calendar.setTime(mDate);
DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.date_picker);
TimePicker timePicker = (TimePicker) dialogView.findViewById(R.id.time_picker);
datePicker.updateDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY));
timePicker.setCurrentMinute(calendar.get(Calendar.MINUTE));
/* This will correctly choose the format coherent with the locale - AM/PM or 24Hrs */
timePicker.setIs24HourView(android.text.format.DateFormat.is24HourFormat(this));
dialogView.findViewById(R.id.date_time_set).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.date_picker);
TimePicker timePicker = (TimePicker) dialogView.findViewById(R.id.time_picker);
Calendar calendar = Calendar.getInstance();
calendar.set(datePicker.getYear(),
datePicker.getMonth(),
datePicker.getDayOfMonth(),
timePicker.getCurrentHour(),
timePicker.getCurrentMinute());
mDate.setTime(calendar.getTimeInMillis());
alertDialog.dismiss();
dateChanged();
}});
alertDialog.setView(dialogView);
alertDialog.show();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment