使用this SO answer到分鐘間隔添加到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();
}
}
}
在回調中,只需將第二個參數的值作爲分鐘,將第三個參數的值作爲秒。
未來版本的Android可能會在「分鐘」微調器設置爲24以上的數字時返回不正確的結果,但我通讀了當前的TimePicker代碼並未發現任何問題。此外,可以使用秒控制器修改或更換am/pm微調器,然後選擇器可以支持小時:分鐘:秒以及分鐘:秒。
對話框中的時間選取器顯示爲時鐘,而不是作爲微調器。模式如何改變? –