Android TimePickerDialog set max time
THIS ANSWER IS OUTDATED
It will not work on Android 5 or higher.
This is an extension to fiddlers answer.
Somehow the onTimeChangedListener is not set by TimePickerDialog in some Android Versions:
ex.
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.2.1_r1.2/android/app/TimePickerDialog.java
The onTimeChanged methode therefor is never called!
Best solution for this issue currently, is propably to code a custom TimePickerDialog with the min/max logic from fiddler.
The more ugly work around is this. (Adding the listener using reflections)
I also update the title to show the currently selected time.
package com.mysuger.android.dialogs;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.content.Context;
import android.widget.TimePicker;
/**
* A time dialog that allows setting a min and max time.
*
*/
public class RangeTimePickerDialog extends TimePickerDialog {
private int minHour = -1;
private int minMinute = -1;
private int maxHour = 25;
private int maxMinute = 25;
private int currentHour = 0;
private int currentMinute = 0;
private Calendar calendar = Calendar.getInstance();
private DateFormat dateFormat;
public RangeTimePickerDialog(Context context, OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) {
super(context, callBack, hourOfDay, minute, is24HourView);
currentHour = hourOfDay;
currentMinute = minute;
dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
try {
Class<?> superclass = getClass().getSuperclass();
Field mTimePickerField = superclass.getDeclaredField("mTimePicker");
mTimePickerField.setAccessible(true);
TimePicker mTimePicker = (TimePicker) mTimePickerField.get(this);
mTimePicker.setOnTimeChangedListener(this);
} catch (NoSuchFieldException e) {
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
}
}
public void setMin(int hour, int minute) {
minHour = hour;
minMinute = minute;
}
public void setMax(int hour, int minute) {
maxHour = hour;
maxMinute = minute;
}
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
boolean validTime = true;
if (hourOfDay < minHour || (hourOfDay == minHour && minute < minMinute)){
validTime = false;
}
if (hourOfDay > maxHour || (hourOfDay == maxHour && minute > maxMinute)){
validTime = false;
}
if (validTime) {
currentHour = hourOfDay;
currentMinute = minute;
}
updateTime(currentHour, currentMinute);
updateDialogTitle(view, currentHour, currentMinute);
}
private void updateDialogTitle(TimePicker timePicker, int hourOfDay, int minute) {
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
String title = dateFormat.format(calendar.getTime());
setTitle(title);
}
}
Datepicker and timepicker - set max and min values
try this:
btnDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
}
};
Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
final DatePickerDialog datePickerDialog = new DatePickerDialog(
Main23Activity.this, datePickerListener,
mYear, mMonth, mDay);
DatePicker datePicker = datePickerDialog.getDatePicker();
c.add(Calendar.MONTH, +1);
long oneMonthAhead = c.getTimeInMillis();
datePicker.setMaxDate(oneMonthAhead);
datePicker.setMinDate(System.currentTimeMillis() - 1000);
datePickerDialog.show();
}
});
btnTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hour, int minute) {
}
};
Calendar c = Calendar.getInstance();
final TimePickerDialog timePickerDialog = new TimePickerDialog(Main23Activity.this,timePickerListener,
c.get(Calendar.HOUR_OF_DAY),c.get(Calendar.MINUTE)+5,false);
timePickerDialog.show();
}
});
You need to check if the user selects today date and the time is less than the current time condition though.
How to set Maximum and Minimum Time Limit for TimePickerDialog for the user to choose within a certain Hour Range?
You can set a TimeChangedListener and override its onTimeChanged
method to set the hour to the closest allowed hour using setHour
.
For example this will force the selected hour to be between 12(12pm) and 15(3pm):
mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker timePicker, int hourOfDay, int minute) {
if(hourOfDay < 12) {
timePicker.setHour(12);
}
else if(hourOfDay > 15) {
timePicker.setHour(15);
}
}
});
How to set minimum time to system current time from timepickerdialog
Thanks for everyone's help. But somehow i solved the issue with the following approach so i guess that will help future researchers to get a solution.
At first when user picks date from the date picker and sets date and selects time picker then it generates a date from simple date format and matches if the both dates are same. if yes then it starts check the time with another dateformat.
here is the code of it. I included everything from date picker.
(Button_name_for_date_picker).setOnClickListener(view -> {
Calendar calendar1 = Calendar.getInstance();
int year = calendar1.get(Calendar.YEAR);
int month = calendar1.get(Calendar.MONTH);
int day = calendar1.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(OrderConfirmationActivity.this,
dateSetListener, year, month, day);
dialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
dialog.getDatePicker().setMaxDate(System.currentTimeMillis() -1000 + (1000*60*60*24*7)); // This allows user to select a date range between a week
dialog.show();
});
dateSetListener = (view, year, month, dayOfMonth) -> {
month = month + 1;
if (month < 10){
String single_month = "0" + month;
(String_name) = dayOfMonth + "/" + single_month + "/" + year;
(Button_name).setText(AppointmentDate);
Appoint_date.setTextColor(getResources().getColor(android.R.color.holo_green_light, getTheme()));
}else{
AppointmentDate = dayOfMonth + "/" + month + "/" + year;
Appoint_date.setText(AppointmentDate);
Appoint_date.setTextColor(getResources().getColor(android.R.color.holo_green_light, getTheme()));
}
};
//This Generates AppointmentTime
Appoint_time.setOnClickListener(view -> {
Calendar calendar12 = Calendar.getInstance();
final int hour = calendar12.get(Calendar.HOUR_OF_DAY);
int minute = calendar12.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(OrderConfirmationActivity.this, (timePicker, selected_hour, selected_minute) -> {
SimpleDateFormat current_date = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
String check = current_date.format(new Date());
if (AppointmentDate.equals(check)){
SimpleDateFormat current_time = new SimpleDateFormat("HH", Locale.getDefault());
int check_hour = Integer.parseInt(current_time.format(new Date()));
String v = String.valueOf(future_time);
Toast.makeText(this, v, Toast.LENGTH_SHORT).show();
if (selected_hour < check_hour) {
future_time = 1;
String v1 = String.valueOf(future_time);
Toast.makeText(this, v1, Toast.LENGTH_SHORT).show();
}
}
if (selected_hour < 7){
time_check = 1;
}else if (selected_hour >= 19){
time_check = 1;
}
if (selected_hour > 12) {
AppointmentTime = (selected_hour - 12) + ":" + selected_minute + " " + "PM";
Appoint_time.setText(AppointmentTime);
} else if (selected_hour == 12) {
AppointmentTime = "12" + ":" + selected_minute + " " + "PM";
Appoint_time.setText(AppointmentTime);
} else {
if (selected_hour != 0) {
AppointmentTime = selected_hour + ":" + selected_minute + " " + "AM";
Appoint_time.setText(AppointmentTime);
} else {
AppointmentTime = "12" + ":" + selected_minute + " " + "AM";
Appoint_time.setText(AppointmentTime);
}
}
}, hour, minute, false);
timePickerDialog.show();
});
how to set max timepicker limit based on datepicker android studio
You can check selected date is Saturday or not using below code:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, monthOfYear);// you have increased value of monthOfYear by using ++monthOfYear so you have to use monthOfYear-1
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
isSaturday = cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY;
and pass this boolean to your timePicker(false, isSaturday) function. In timePicker function you can set maxHours:
int maxHour = 15;
if(isSaturday){
maxHour=12
}
Related Topics
How to Add a Badge to an Application Icon in Android
Listview with Clickable/Editable Widget
How to Get String from Different Locales in Android
Android Studio Gradle Configuration with Name 'Default' Not Found
What Kind of Font Files Do I Need for Modern Browsers, Android and iOS
How to Change the Color of Header Bar and Address Bar in Newest Chrome Version on Lollipop
How to Autoplay HTML5 Mp4 Video on Android
Html: Why Does Android Browser Show "Go" Instead of "Next" in Keyboard
How Much Support Is There for -Webkit-Overflow-Scrolling:Touch
Android Log.V(), Log.D(), Log.I(), Log.W(), Log.E() - When to Use Each One
How to View Androidmanifest.Xml from APK File
Adb Not Responding - Wait More or Kill Adb or Restart (Ubuntu 13) 64-Bit
Difficulties with Calling an Android Ndk Function from Directly Delphi
Do X86 Android Avd's Work on Linux on Amd
How to Change Endianness Mid-Execution on Arm (Android/Linux)