在使用此 SO 答案向 TimePickerDialog 添加分钟间隔后,我创建了一个类似的子类,将小时微调器的范围扩展到 0-60 并将小时:分钟微调器视为分钟:秒:
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.NumberPicker;
import android.widget.TimePicker;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class DurationPicker extends TimePickerDialog {
private TimePicker timePicker;
private final OnTimeSetListener callback;
private int initialMinutes;
public DurationPicker(Context context, OnTimeSetListener callBack, int minutes, int seconds) {
super(context, callBack, minutes, seconds, true); // the last argument removes the am/pm spinner
this.callback = callBack;
this.initialMinutes = minutes; // we'll have to set this again after modifying the "hours" spinner
this.setTitle("Set duration");
}
@Override
public void onClick(DialogInterface dialog, int which) {
if (callback != null && timePicker != null) {
timePicker.clearFocus();
callback.onTimeSet(timePicker, timePicker.getCurrentHour(), timePicker.getCurrentMinute());
}
}
@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("hour");
// modify the hours spinner to cover the maximum number of minutes we want to support
int maxMinutes = 60;
NumberPicker mHourSpinner = (NumberPicker)timePicker.findViewById(field.getInt(null));
mHourSpinner.setMinValue(0);
mHourSpinner.setMaxValue(maxMinutes);
List<String> displayedValues = new ArrayList<String>();
for (int i = 0; i <= maxMinutes; i++) {
displayedValues.add(String.format("%d", i));
}
mHourSpinner.setDisplayedValues(displayedValues.toArray(new String[0]));
mHourSpinner.setValue(initialMinutes); // we can set this again now that we've modified the hours spinner
} catch (Exception e) {
e.printStackTrace();
}
}
}
在回调中,只需将第二个参数的值视为分钟,将第三个参数的值视为秒。
当“分钟”微调器设置为大于 24 的数字时,未来版本的 Android 可能会返回不正确的结果,但我通读了当前的 TimePicker 代码并没有发现任何问题。此外,可以用秒微调器修改或替换上午/下午微调器,然后选择器可以支持小时:分钟:秒以及分钟:秒。