Show TimePicker with minutes intervals in android
Use the following the custom class called CustomTimePickerDialog
, which I think solve your problem.
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.NumberPicker;
import android.widget.TimePicker;
public class CustomTimePickerDialog extends TimePickerDialog {
private final static int TIME_PICKER_INTERVAL = 5;
private TimePicker mTimePicker;
private final OnTimeSetListener mTimeSetListener;
public CustomTimePickerDialog(Context context, OnTimeSetListener listener,
int hourOfDay, int minute, boolean is24HourView) {
super(context, TimePickerDialog.THEME_HOLO_LIGHT, null, hourOfDay,
minute / TIME_PICKER_INTERVAL, is24HourView);
mTimeSetListener = listener;
}
@Override
public void updateTime(int hourOfDay, int minuteOfHour) {
mTimePicker.setCurrentHour(hourOfDay);
mTimePicker.setCurrentMinute(minuteOfHour / TIME_PICKER_INTERVAL);
}
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case BUTTON_POSITIVE:
if (mTimeSetListener != null) {
mTimeSetListener.onTimeSet(mTimePicker, mTimePicker.getCurrentHour(),
mTimePicker.getCurrentMinute() * TIME_PICKER_INTERVAL);
}
break;
case BUTTON_NEGATIVE:
cancel();
break;
}
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
try {
Class<?> classForid = Class.forName("com.android.internal.R$id");
Field timePickerField = classForid.getField("timePicker");
mTimePicker = (TimePicker) findViewById(timePickerField.getInt(null));
Field field = classForid.getField("minute");
NumberPicker minuteSpinner = (NumberPicker) mTimePicker
.findViewById(field.getInt(null));
minuteSpinner.setMinValue(0);
minuteSpinner.setMaxValue((60 / TIME_PICKER_INTERVAL) - 1);
List<String> displayedValues = new ArrayList<>();
for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
displayedValues.add(String.format("%02d", i));
}
minuteSpinner.setDisplayedValues(displayedValues
.toArray(new String[displayedValues.size()]));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here is the demonstrating screenshot.
How to get 30 min interval in time picker in Android N
I have resolved my issue using this library and here is my complete code which may help someone in the future.
My complete code is in below.
public class MainActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
private TextView timeTextView;
private TimePickerDialog timePickerDialog;
private Button timeButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find our View instances
timeTextView = findViewById(R.id.time_textview);
timeButton = findViewById(R.id.time_button);
// Show a timepicker when the timeButton is clicked
timeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar now = Calendar.getInstance();
timePickerDialog = TimePickerDialog.newInstance(
MainActivity.this,
now.get(Calendar.HOUR_OF_DAY),
now.get(Calendar.MINUTE),
false
);
timePickerDialog.setThemeDark(false);
timePickerDialog.setTitle("TimePicker Title");
timePickerDialog.setTimeInterval(1, 30, 60);
timePickerDialog.setAccentColor(Color.parseColor("#9C27B0"));
timePickerDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface)
Log.d("TimePicker", "Dialog was cancelled");
}
});
timePickerDialog.show(getFragmentManager(), "Timepickerdialog");
}
});
}
@Override
public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
updateEndTime(hourOfDay,minute);
}
private void updateEndTime(int hours, int mins) {
String timeSet = "";
if (hours > 12) {
hours -= 12;
timeSet = "PM";
} else if (hours == 0) {
hours += 12;
timeSet = "AM";
} else if (hours == 12) {
timeSet = "PM";
} else {
timeSet = "AM";
}
// Append in a StringBuilder
String aTime = new StringBuilder().append(pad(hours)).append(':')
.append(pad(mins)).append(" ").append(timeSet).toString();
timeTextView.setText(aTime);
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
@Override
public void onResume() {
super.onResume();
TimePickerDialog tpd = (TimePickerDialog) getFragmentManager().findFragmentByTag("Timepickerdialog");
if (tpd != null) tpd.setOnTimeSetListener(this);
}
}
My desire output is like this:
Android N,L and below timepicker with minute interval
Indeed creating my own timepicker was the solution. I'm posting my solution below for others. This creates a timepicker dialog with minute intervals for api 14 and above. It is working for intervals of 1,5 and 15. Other values may also work.
Usage:
Dialog intervalTimePickerDialog = IntervalTimePickerDialogFactory.getIntervalTimePickerDialog(Context context, int positiveTextId, TimePickerDialog.OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView, final int interval);
intervalTimePickerDialog .show();
I think it won't need much explanation. int positiveTextId
can be removed, it was just something I needed.
timepickerdialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TimePicker
android:timePickerMode="spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/timePicker"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/timePicker"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
style="?android:attr/borderlessButtonStyle"
android:id="@+id/buttonNegative" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inklokken"
style="?android:attr/borderlessButtonStyle"
android:id="@+id/buttonPositive" />
</LinearLayout>
</RelativeLayout>
Code:
public class IntervalTimePickerDialogFactory {
public static Dialog getIntervalTimePickerDialog(Context context, int positiveTextId, TimePickerDialog.OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView, final int interval){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
return new LIntervalTimePickerDialog(context, positiveTextId, callBack, hourOfDay, minute, is24HourView, interval);
}else{
return new IntervalTimePickerDialog(context, positiveTextId, callBack, hourOfDay, minute, is24HourView, interval);
}
}
private static class IntervalTimePickerDialog extends TimePickerDialog {
private TimePicker timePicker;
private final OnTimeSetListener callback;
private int interval;
public IntervalTimePickerDialog(Context context, int positiveTextId, OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView, final int interval) {
super(context, TimePickerDialog.THEME_HOLO_LIGHT, callBack, hourOfDay, ((int)Math.ceil((double)minute/(double)interval)), is24HourView);
this.interval = interval;
this.callback = callBack;
this.setButton(BUTTON_POSITIVE, context.getResources().getString(positiveTextId), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (callback != null && timePicker != null) {
timePicker.clearFocus();
callback.onTimeSet(timePicker, timePicker.getCurrentHour(),
timePicker.getCurrentMinute() * interval);
}
}
});
this.setButton(BUTTON_NEGATIVE, context.getResources().getString(R.string.annuleren), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
});
}
@Override
protected void onStop() {
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
try {
Class<?> classForid = Class.forName("com.android.internal.R$id");
Field timePickerField = classForid.getField("timePicker");
this.timePicker = (TimePicker) findViewById(timePickerField
.getInt(null));
Field field = classForid.getField("minute");
NumberPicker mMinuteSpinner = (NumberPicker) timePicker
.findViewById(field.getInt(null));
mMinuteSpinner.setMinValue(0);
mMinuteSpinner.setMaxValue((60 / interval) - 1);
List<String> displayedValues = new ArrayList<>();
for (int i = 0; i < 60; i += interval) {
displayedValues.add(String.format("%02d", i));
}
mMinuteSpinner.setDisplayedValues(displayedValues
.toArray(new String[0]));
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static class LIntervalTimePickerDialog extends Dialog{
private static final DecimalFormat FORMATTER = new DecimalFormat("00");
private final TimePickerDialog.OnTimeSetListener callback;
private int interval;
private TimePicker timePicker;
private NumberPicker minutePicker;
public LIntervalTimePickerDialog(Context context, int positiveTextId, TimePickerDialog.OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView, final int interval) {
super(context);
setContentView(R.layout.timepickerdialog);
timePicker = (TimePicker) findViewById(R.id.timePicker);
timePicker.setIs24HourView(is24HourView);
timePicker.setCurrentHour(hourOfDay);
this.callback = callBack;
this.interval = interval;
Button buttonPositive = (Button) findViewById(R.id.buttonPositive);
buttonPositive.setText(positiveTextId);
buttonPositive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (callback != null && timePicker != null) {
timePicker.clearFocus();
callback.onTimeSet(timePicker, timePicker.getCurrentHour(),
timePicker.getCurrentMinute() * interval);
}
dismiss();
}
});
Button buttonNegative = (Button) findViewById(R.id.buttonNegative);
buttonNegative.setText(context.getResources().getString(R.string.annuleren));
buttonNegative.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
setMinutePicker();
timePicker.setCurrentMinute((int) Math.ceil((double) minute / (double) interval));
}
public void setMinutePicker() {
int numValues = 60 / interval;
String[] displayedValues = new String[numValues];
for (int i = 0; i < numValues; i++) {
displayedValues[i] = FORMATTER.format(i * interval);
}
View minute = timePicker.findViewById(Resources.getSystem().getIdentifier("minute", "id", "android"));
if ((minute != null) && (minute instanceof NumberPicker)) {
minutePicker = (NumberPicker) minute;
minutePicker.setMinValue(0);
minutePicker.setMaxValue(numValues - 1);
minutePicker.setDisplayedValues(displayedValues);
}
}
}
}
Related Topics
How to Downgrade My Sdk Version
How to Change the Default Icon on the Searchview, to Be Use in the Action Bar on Android
Execution Failed for Task 'App:Mergedebugresources' Crunching Cruncher....Png Failed
Use Uri Builder in Android or Create Url with Variables
Firebase (Fcm) How to Get Token
Google Play Game Services - Unable to Sign In
Permission Denial: This Requires Android.Permission.Interact_Across_Users_Full
How to Scale a Website for Mobile Devices
Calculating Distance Between Two Geographic Locations
Install_Failed_Update_Incompatible When I Try to Install Compiled .Apk on Device
Android How to Display 2 Listviews in One Activity One After the Other
How to Display Progress Dialog Before Starting an Activity in Android
Why Do I Get Access Denied to Data Folder When Using Adb
How to Use Assert on Android Devices
Wifi Connect-Disconnect Listener
How to Convert Image into Byte Array and Byte Array to Base64 String in Android