gpt4 book ai didi

Android TimePickerDialog 设置最大时间

转载 作者:IT老高 更新时间:2023-10-28 22:24:27 28 4
gpt4 key购买 nike

我正在寻找一种方法来设置 Android TimePickerDialog 上可选择的最大和最小时间,并将默认分钟间隔从 1 分钟更改为 5 分钟,

我认为这很容易,但我找不到方法!

最佳答案

此答案已过时

它不适用于 Android 5 或更高版本。


这是 fiddler 答案的扩展。在某些 Android 版本中,TimePickerDialog 不知何故未设置 onTimeChangedListener:

例如。 http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.2.1_r1.2/android/app/TimePickerDialog.java

永远不会调用 onTimeChanged 方法!目前这个问题的最佳解决方案是使用 fiddler 的最小/最大逻辑编写自定义 TimePickerDialog。

更丑陋的解决方法是这个。 (使用反射添加监听器)我还更新了标题以显示当前选择的时间。

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);
}
}

关于Android TimePickerDialog 设置最大时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13516389/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com