How to set 1 timepicker in 2 different EditText? - java

I have 2 edit text fields one for starting time and one for ending time. And I have written
a single java function for time picker for both of the edit text fields.
The issue is when I try to set time in the ending time edit text field it sets time to the starting time
edit text field.
This my xml code:
<androidx.appcompat.widget.AppCompatEditText
android:id="#+id/starting_time_et"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="305dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:hint="Click To Add Starting Time Of Course"
android:textStyle="bold">
</androidx.appcompat.widget.AppCompatEditText>
<androidx.appcompat.widget.AppCompatEditText
android:id="#+id/ending_time_et"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="355dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:hint="Click To Add Ending Time Of Course"
android:textStyle="bold">
This is my java code for time picker:
Button backButton;
EditText startingTime;
EditText endingTime;
TimePickerDialog timePickerDialog;
Calendar calender;
int currentHour;
int currentMinute;
String amPm;
String minuteWith_0_OnLeft;
startingTime = findViewById(R.id.starting_time_et);
startingTime.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
startingTimeAndEndingTime();
timePickerDialog.show();
}
});
endingTime = findViewById(R.id.ending_time_et);
endingTime.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
startingTimeAndEndingTime();
timePickerDialog.show();
}
});
public void startingTimeAndEndingTime(){
calender = Calendar.getInstance();
currentHour = calender.get(Calendar.HOUR_OF_DAY);
currentMinute = calender.get(Calendar.MINUTE);
timePickerDialog = new TimePickerDialog(AddCourses.this, new
TimePickerDialog.OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute){
if(hourOfDay > 12)
{
hourOfDay -= 12;
amPm = "Pm";
}
else if(hourOfDay == 0)
{
hourOfDay += 12;
amPm = "Am";
}
else if(hourOfDay == 12)
{
amPm = "Pm";
}
else
{
amPm = "AM";
}
if( minute < 10 )
{
minuteWith_0_OnLeft = "0" + minute;
}
else
{
minuteWith_0_OnLeft = String.valueOf(minute);
}
startingTime.setText(MessageFormat.format("{0}:{1}{2}", hourOfDay, minuteWith_0_OnLeft, amPm));
}
}, currentHour, currentMinute, false);
}

The code is working as expected. You are setting the text of the startingTime EditText in startingTimeAndEndingTime() function and calling it from both startingTime and endingTime click listener. To fix this you can modify your your startingTimeAndEndingTime() function like this.
public void startingTimeAndEndingTime(boolean isStart) {
calender = Calendar.getInstance();
currentHour = calender.get(Calendar.HOUR_OF_DAY);
currentMinute = calender.get(Calendar.MINUTE);
timePickerDialog = new TimePickerDialog(AddCourses.this, new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute)
{
if(hourOfDay > 12)
{
hourOfDay -= 12;
amPm = "Pm";
}
else if(hourOfDay == 0)
{
hourOfDay += 12;
amPm = "Am";
}
else if(hourOfDay == 12)
{
amPm = "Pm";
}
else
{
amPm = "AM";
}
if( minute < 10 )
{
minuteWith_0_OnLeft = "0" + minute;
}
else
{
minuteWith_0_OnLeft = String.valueOf(minute);
}
if (isStart) {
startingTime.setText(MessageFormat.format("{0}:{1}{2}", hourOfDay, minuteWith_0_OnLeft, amPm));
} else {
endingTime.setText(MessageFormat.format("{0}:{1}{2}", hourOfDay, minuteWith_0_OnLeft, amPm));
}
}
}, currentHour, currentMinute, false);
}

Let my startingTimeAndEndingTime Function accept an EditText parameter like this:
public void startingTimeAndEndingTime(EditText editText)
And then inside that method, replace startingTime.setText(MessageFormat.format("{0}:{1}{2}", hourOfDay, minuteWith_0_OnLeft, amPm)); with this:
editText.setText(MessageFormat.format("{0}:{1}{2}", hourOfDay, minuteWith_0_OnLeft, amPm));
Now in onClick of startingTime and endingTime, call the method like this, for startingTime:
startingTimeAndEndingTime(startingTime);
and for endingTime:
startingTimeAndEndingTime(endingTime);
SO my code will be like this:
startingTime = findViewById(R.id.starting_time_et);
startingTime.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startingTimeAndEndingTime( startingTime );
timePickerDialog.show();
}
});
endingTime = findViewById(R.id.ending_time_et);
endingTime.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startingTimeAndEndingTime( endingTime );
timePickerDialog.show();
}
});
public void startingTimeAndEndingTime( EditText startingAndEndingTImeEt )
{
calender = Calendar.getInstance();
currentHour = calender.get(Calendar.HOUR_OF_DAY);
currentMinute = calender.get(Calendar.MINUTE);
timePickerDialog = new TimePickerDialog(AddCourses.this, new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute)
{
if(hourOfDay > 12)
{
hourOfDay -= 12;
amPm = "Pm";
}
else if(hourOfDay == 0)
{
hourOfDay += 12;
amPm = "Am";
}
else if(hourOfDay == 12)
{
amPm = "Pm";
}
else
{
amPm = "AM";
}
if( minute < 10 )
{
minuteWith_0_OnLeft = "0" + minute;
}
else
{
minuteWith_0_OnLeft = String.valueOf(minute);
}
//startingTime.setText(hourOfDay + ":" + minute + amPm);
startingAndEndingTImeEt.setText(MessageFormat.format("{0}:{1}{2}", hourOfDay, minuteWith_0_OnLeft, amPm));
}
}, currentHour, currentMinute, false);
}

Related

Android Date Time picker in one dialog

I am using material Date Time picker for my Android app. But I want to combine the Date and Time picker in one dialog.
I am following this one. But I need to select the time right after the date selection.
Please suggest possible way to do this one.
You can call TimePicker after DatePicker set Date. Like this..
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();
}
});
Date Picker:
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();
}
Time Picker
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();
}
--
Kotlin
Here's the tested Kotlin code for combining the DatePickerDialog and TimePickerDialog together. It becomes simpler because of the support of the closures in Kotlin. The following function should be placed in your Fragment or Activity. The requireContext() method is a member of Fragment. If you are using Activity, use applicationContext instead.
private fun pickDateTime() {
val currentDateTime = Calendar.getInstance()
val startYear = currentDateTime.get(Calendar.YEAR)
val startMonth = currentDateTime.get(Calendar.MONTH)
val startDay = currentDateTime.get(Calendar.DAY_OF_MONTH)
val startHour = currentDateTime.get(Calendar.HOUR_OF_DAY)
val startMinute = currentDateTime.get(Calendar.MINUTE)
DatePickerDialog(requireContext(), DatePickerDialog.OnDateSetListener { _, year, month, day ->
TimePickerDialog(requireContext(), TimePickerDialog.OnTimeSetListener { _, hour, minute ->
val pickedDateTime = Calendar.getInstance()
pickedDateTime.set(year, month, day, hour, minute)
doSomethingWith(pickedDateTime)
}, startHour, startMinute, false).show()
}, startYear, startMonth, startDay).show()
}
Call the above function in onClickListener of your button as following:
button.setOnClickListener { pickDateTime() }
That's it!
If you want to show clock in 12 hour or 24 hour format depending on user's settings, replace false with DateFormat.is24HourFormat(requireContext())
Try this 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 day,
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);
}
}
In your Activity :
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 day,
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();
}
});
}
}
Googled this problem and found usefull Enamul Haque's answer. Modified his code little bit and got this result. Its quick solution and will be improved, but works nice)
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;
}
}
Dialogs calls via method showDialog(...), possible to release object when it not need anymore (in onDestroy() in activity f.e).
And again - thanks Enamul Haque for idea.
This answer is basically an improvement in answer given by #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 day,
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>
DialogTheme style
<style name="DialogTheme">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
Calling code
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();
If you need to select the time right after the date selection you can simply show TimePickerDialog automatically after date is selected. This is the easiest way.
While you have listener that is fired when date is selected with selected date, you can simply pass that selected date to TimePickerDialog and with a few customization in mdtp_time_picker_dialog.xml you can add a TextView to show the selected text.
Another option is merging mdtp_time_picker_dialog.xml and mdtp_date_picker_dialog.xml that are root layouts for date picker dialog and time picker dialog. You can set time picker part visibility as GONE and switch the visibility when you want to switch pickers.
The second solution is more difficult to implement because in addition to layouts, you have to merge all controls and listeners.
If you want the user to see both of the pickers, I think you actually need to design a new view yourself. That library layouts is not suitable for this.
Use this simple code.. I'm using this code in my Project..
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();
You Can Get Date And Time One By One Using Pickers In Android.
Calendar getDate = Calendar.getInstance();
cDay = getDate.get(Calendar.DAY_OF_MONTH);
cMonth = getDate.get(Calendar.MONTH);
cYear = getDate.get(Calendar.YEAR);
timePickerDialog = new TimePickerDialog(DesignActivity.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
final String AM_PM ;
if (hourOfDay > 12) {
hourOfDay -= 12;
AM_PM = "pm";
} else if (hourOfDay == 0) {
hourOfDay += 12;
AM_PM = "am";
} else if (hourOfDay == 12)
AM_PM = "pm";
else
AM_PM = "am";
hour1 = hourOfDay;
minutes1 = minute;
DatePickerDialog datePicker = new DatePickerDialog(DesignActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
cYear = year;
cMonth = month;
cDay = dayOfMonth;
editText.setText(hour1 + ":" +minutes1 + AM_PM + " " + cDay + "/" + cMonth + "/" + cYear);
}
},cYear,cMonth,cDay);
datePicker.show();
}
},hour1,minutes1,false);
timePickerDialog.show();
}
});
If You Will Need More Explanation About
Click This.
Based on #Yogesh Umesh Vaity's answer, I made an object for showing a DateTimePicker in Kotlin.
class DateTimePicker(val context: Context, var pickTime:Boolean = false, var calendar: Calendar = Calendar.getInstance(),
var callback: (it : DateTimePicker) -> Unit) {
companion object{
#JvmStatic
fun getFormat(format : String) : String{
when(format){
"d" -> return "dd/MM/yyyy"
"t" -> return "HH:mm"
"dt" -> return "dd/MM/yyyy HH:mm"
}
return "dd/MM/yyyy"
}
}
fun show(){
val startYear = calendar.get(Calendar.YEAR)
val startMonth = calendar.get(Calendar.MONTH)
val startDay = calendar.get(Calendar.DAY_OF_MONTH)
val startHour = calendar.get(Calendar.HOUR_OF_DAY)
val startMinute = calendar.get(Calendar.MINUTE)
DatePickerDialog(context, DatePickerDialog.OnDateSetListener { _, year, month, day ->
if(pickTime) {
TimePickerDialog(context, TimePickerDialog.OnTimeSetListener { _, hour, minute ->
calendar.set(year, month, day, hour, minute)
callback(this)
}, startHour, startMinute, true).show()
} else {
calendar.set(year,month,day)
callback(this)
}
}, startYear, startMonth, startDay).show()
}
fun showTime(){
val startYear = calendar.get(Calendar.YEAR)
val startMonth = calendar.get(Calendar.MONTH)
val startDay = calendar.get(Calendar.DAY_OF_MONTH)
val startHour = calendar.get(Calendar.HOUR_OF_DAY)
val startMinute = calendar.get(Calendar.MINUTE)
TimePickerDialog(context, TimePickerDialog.OnTimeSetListener { _, hour, minute ->
calendar.set(startYear, startMonth, startDay, hour, minute)
callback(this)
}, startHour, startMinute, true).show()
}
}
You could use the object from your Activity like this:
// Open Date Picker only and set an EditText
DateTimePicker(this){
val sdf = SimpleDateFormat(DateTimePicker.getFormat("d"), Locale.getDefault())
editText.setText(sdf.format(it.calendar.time))
}.show()
// Open Date Picker then Time picker and set an EditText
DateTimePicker(this, true){
val sdf = SimpleDateFormat(DateTimePicker.getFormat("dt"), Locale.getDefault())
editText.setText(sdf.format(it.calendar.time))
}.show()
// Open Time Picker only and set an EditText
DateTimePicker(this){
val sdf = SimpleDateFormat(DateTimePicker.getFormat("t"), Locale.getDefault())
editText.setText(sdf.format(it.calendar.time))
}.showTime()
// Use your own calendar object if you prefer to use your pre-configured calendar
val myCalendar = Calendar.getInstance()
myCalendar.set(Calendar.YEAR, 1995)
DateTimePicker(this, false, myCalendar){
val sdf = SimpleDateFormat(DateTimePicker.getFormat("d"), Locale.getDefault())
editText.setText(sdf.format(it.calendar.time))
}.show()

Don't understand how to correct mistake in datepicker code

I am not able to understand where am I doing mistake. I want to check it is a weekend or weekday. If it is weekend then it should prompt in the toast that it is a sunday or saturday weekend. I don't know what should I put in place of ??? mark. It should also display current date if it is weekend. Please, any one can help me. Thank you.
View.OnClickListener//,
// TimePickerDialog.OnTimeSetListener
// TimePickerDialog.OnTimeSetListener
{
//Declaration for class
ButtonViews views;
dpListener dpListenerView;
// Declartion for member vairables
int day, month, x_year;
int hour;
int minute;
Calendar calendar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
views = new ButtonViews();
dpListenerView = new dpListener();
//ButtonListener
views.button_date.setOnClickListener(this);
views.button_time.setOnClickListener(this);
//
// pick up the default date using Calender class
calendar = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
/*
day = calendar.get(Calendar.DAY_OF_MONTH);
month = calendar.get(Calendar.MONTH);
x_year = calendar.get(Calendar.YEAR);
*/
curr_date();
hour = calendar.get(Calendar.HOUR_OF_DAY);
minute = calendar.get(Calendar.MINUTE);
setupDate(day, month, x_year);
setupTime(hour, minute);
}
public void curr_date(){
day = calendar.get(Calendar.DAY_OF_MONTH);
month = calendar.get(Calendar.MONTH);
x_year = calendar.get(Calendar.YEAR);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_date:
showDatePickerDialog();
break;
case R.id.button_time:
break;
}
}
private void setupTime(int hours, int minutes) {
views.button_time.setText(hours + ":" + minutes);
}
private void setupDate(int day, int month, int year) {
String strMonth = ((month + 1) <= 9) ? ("0" + (month + 1)) : String.valueOf(month + 1);
views.button_date.setText(String.valueOf(day) + "/" + strMonth + "/" + String.valueOf(year));
}
private void showDatePickerDialog() {
DatePickerDialog datepickerdialog = new DatePickerDialog
(
this,
dpListenerView,
/* new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
} },*/
//this,
x_year,
month,
day
);
datepickerdialog.show();
}
class ButtonViews {
Button button_time;
Button button_date;
public ButtonViews() {
button_date = (Button) findViewById(R.id.button_date);
button_time = (Button) findViewById(R.id.button_time);
}
}
class dpListener implements OnDateSetListener {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar c = Calendar.getInstance();
// c.setTime();
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
if(dayOfWeek == 7 || dayOfWeek == 1) {
// as your requirement: you should display mesage they can not select the weekend" here
// then you set the value in datepickerdialog by current date
Toast.makeText(DateTimePickerActivity.this
, "You have selected weekend"
, Toast.LENGTH_SHORT).show();
}
}
}
}
Once you get your date you can do like this and get the day and proceed with your logic.
Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
I think that your variable dayOfWeek is the same variable as the parameter dayOfMonth
The above code must work
public DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
if (selectedDay == 1 || selectedDay == 7) {
Toast.makeText(DateTimePickerActivity.this
, "You have selected weekend"
, Toast.LENGTH_SHORT).show();
view.updateDate(selectedYear,selectedMonth,selectedDay);
}
}
};

How to set custom Time in TimePicker

TimePicker shows current time as default in TimePicker, but what if i want to set default time in time picker as per my requirement.
Like its 11:10 when i am writing this, but in TimePicker i like to show 01:00 as default (my mean 2 hours difference, and minutes should be 00 only)
static final int TIME_DIALOG_ID = 1;
public int year,month,day,hour,minute;
private int mYear, mMonth, mDay,mHour,mMinute;
public TimePickerActivity() {
// Assign current Date and Time Values to Variables
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);
}
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int min) {
hour = hourOfDay;
minute = min;
String formattedMinutes = "" + min;
String formattedHour = "" + hourOfDay;
if (hourOfDay < 10) {
formattedHour = "0" + hourOfDay;
}
if (min < 10) {
formattedMinutes = "0" + min;
}
textTime.setText(formattedHour + ":" + formattedMinutes);
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
TimePickerDialog timePickerDialog = new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false);
return timePickerDialog;
}
return null;
}
You can do this with following code:
private TimePicker timePicker;
timePicker = (TimePicker) dialog.findViewById(R.id.timePickerDialog);
if(DateFormat.is24HourFormat(getActivity()){
timePicker.setIs24HourView(true);
}else {
timePicker.setIs24HourView(false);
}
// here you can define your hour and minute value.
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(minute);
You can try below code
SimpleDateFormat sdf = new SimpleDateFormat("hh:ss");
Date date = null;
try {
date = sdf.parse("07:00");
} catch (ParseException e) {
}
Calendar c = Calendar.getInstance();
c.setTime(date);
TimePicker picker = new TimePicker(getApplicationContext());
picker.setCurrentHour(c.get(Calendar.HOUR_OF_DAY));
picker.setCurrentMinute(c.get(Calendar.MINUTE));

DateTime picker on same dialog doesn't accept minDate and maxDate

I have found a tutorial in Google before for Date and Time picker on same dialog. I've trying to set minDate and maxDate on the calendar but nothing help. I want to make when user open dialog to choose date default date to be 4 days ahead from current date. For this I've trying to put
datePicker.setMinDate(System.currentTimeMillis() + 4);
but when I open dialog nothing is changed. The code is a little bit long and I will try to post only what I think is needed. This is CustomDateTimePicker.java
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;
}
}
And this is in MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.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) {
((EditText) findViewById(R.id.datePicker)).setText(calendarSelected.get(Calendar.DAY_OF_MONTH)
+ "-" + (monthNumber+1) + "-" + year
+ " " + hour24 + ":" + min);
}
#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.btnCalendar).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
custom.showDialog();
}
});
I believe this is the part which I need to fix but can't get it how exactly.
In case of need here is the full code of CustomDateTimePicker.java -> http://pastebin.com/UnifiAWu
datePicker.setMinDate(System.currentTimeMillis() + 4);
You are adding 4 milliseconds to the current time and passing that as the minDate. To fix this, you'll have to convert 4 days into milliseconds and add that to your current time.

timePicker with multiple buttons

I hope someone can help me. I lack in OOP knowledge and am a newbie in android.
I have 6 buttons. Each button will call the timePicker and display the time on the button.
How do i want to differentiate each buttons?
Thank you.....
Here's the code..:
public class TabTwo extends Activity implements OnClickListener {
private Button btnBrfkst;
private Button btnMtea;
private Button btnLunch;
private Button btnAftea;
private Button btnDinner;
private Button btnSupper;
private Calendar mCalen;
private int hourOfDay;
private int minute;
private int ampm;
int timePickerInput ;
private static final int Time_PICKER_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_two);
btnBrfkst = (Button) findViewById(R.id.button1);
btnMtea = (Button) findViewById(R.id.button2);
btnLunch = (Button) findViewById(R.id.button3);
btnAftea = (Button) findViewById(R.id.button4);
btnDinner = (Button) findViewById(R.id.button5);
btnSupper = (Button) findViewById(R.id.button6);
mCalen = Calendar.getInstance();
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
btnBrfkst.setOnClickListener(this);
btnMtea.setOnClickListener(this);
btnLunch.setOnClickListener(this);
btnAftea.setOnClickListener(this);
btnDinner.setOnClickListener(this);
btnSupper.setOnClickListener(this);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
switch (id) {
case Time_PICKER_ID:
return new TimePickerDialog(this, TimePickerListener,
hourOfDay, minute, false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener TimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
// while dialog box is closed, below method is called.
public void onTimeSet(TimePicker view, int hour, int minute) {
switch (timePickerInput) {
case R.id.button1:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr = (ampm == 0) ? "AM" : "PM";
// Set the Time String in Button
btnBrfkst.setText(hour12format + " : " + minute + " / " + ampmStr);
break;
case R.id.button2:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format2 = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr2 = (ampm == 0) ? "AM" : "PM";
btnMtea.setText(hour12format2 + " : " + minute + " / " + ampmStr2);
break;
case R.id.button3:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format3 = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr3 = (ampm == 0) ? "AM" : "PM";
btnLunch.setText(hour12format3 + " : " + minute + " / " + ampmStr3);
break;
case R.id.button4:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format4 = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr4 = (ampm == 0) ? "AM" : "PM";
btnAftea.setText(hour12format4 + " : " + minute + " / " + ampmStr4);
break;
case R.id.button5:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format5 = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr5 = (ampm == 0) ? "AM" : "PM";
btnDinner.setText(hour12format5 + " : " + minute + " / " + ampmStr5);
break;
case R.id.button6:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format6 = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr6 = (ampm == 0) ? "AM" : "PM";
btnSupper.setText(hour12format6 + " : " + minute + " / " + ampmStr6);
break;
}
}
};
#Override
public void onClick(View v) {
showDialog(Time_PICKER_ID);
}
}
Your activity or fragment should implements View.OnClickListener.
Then each button should register each button like so:
Button buttonOne = (Button) findViewById(R.id.button_one);
Button buttonTwo = (Button) findViewById(R.id.button_two);
buttonOne.setOnClickListener(this);
buttonTwo.setOnClickListener(this);
Then in your onClick method:
#Override
public void onClick(View temp)
{
switch(temp.getId()) {
case R.id.button_one:
//do something
break;
case R.id.button_two:
//do something
break;
}
}
An other option is to set the method to be called in the layout file for each button using android:onClick="myMethodOne". This way you can call different methods if you want or even the same method and differentiate on ids like you do in the onClick methods.
Change this:
#Override
public void onClick(View v) {
showDialog(Time_PICKER_ID);
}
to
#Override
public void onClick(View v) {
timePickerInput = v.getId();
showDialog(Time_PICKER_ID);
}
You need to set the timerPickerInput to be the id of the button so you know which button to display the time in.

Categories

Resources