在Android中,要在TimePickerDialog中设置自定义分钟间隔,可以通过自定义TimePickerDialog实现。以下是一个示例代码:
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.widget.TimePicker;
import androidx.annotation.NonNull;
public class CustomTimePickerDialog extends TimePickerDialog {
private final int mMinuteInterval;
public CustomTimePickerDialog(@NonNull Context context, int themeResId, int minuteInterval, OnTimeSetListener listener, int hourOfDay, int minute, boolean is24HourView) {
super(context, themeResId, listener, hourOfDay, minute, is24HourView);
mMinuteInterval = minuteInterval;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TimePicker timePicker = (TimePicker) findViewById(android.R.id.timePicker1);
if (timePicker != null) {
timePicker.setMinute(mMinuteInterval * (timePicker.getMinute() / mMinuteInterval));
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
if (minute % mMinuteInterval != 0) {
int newMinute = mMinuteInterval * (minute / mMinuteInterval);
view.setCurrentMinute(newMinute);
}
}
});
}
}
}
在这个示例中,我们创建了一个名为CustomTimePickerDialog的自定义TimePickerDialog类,并在其中设置了一个名为mMinuteInterval的成员变量,用于存储自定义的分钟间隔。
在onCreate方法中,我们获取了TimePicker控件,并设置了其分钟间隔。我们还添加了一个OnTimeChangedListener,以确保在用户更改分钟时,分钟值始终是自定义分钟间隔的倍数。
要使用此自定义TimePickerDialog,请在您的代码中创建一个新的CustomTimePickerDialog实例,并传递所需的参数,包括自定义分钟间隔。例如:
int minuteInterval = 15;
CustomTimePickerDialog timePickerDialog = new CustomTimePickerDialog(this, null, minuteInterval, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// 处理用户设置的时间
}
}, 12, 0, true);
timePickerDialog.show();
这将创建一个具有自定义分钟间隔为15分钟的TimePickerDialog,并在用户设置时间时调用OnTimeSetListener。
领取专属 10元无门槛券
手把手带您无忧上云