我是Android的新手,我想不允许使用时间选择器挑选过去的时间.. 我尝试使用以下代码
private TimePicker.OnTimeChangedListener StartTimeChangedListener=new TimePicker.OnTimeChangedListener()
{
public void onTimeChanged(TimePicker view,int selectedHour,int selectedMinute)
{
update(view,selectedHour,selectedMinute);
}
};
我不知道如何编写更新代码(view,selectedHour,selectedMinute);任何人都可以帮助我...
答案 0 :(得分:2)
您是否尝试过关注时间戳的tutorial on the developers page?
修改强>
好的,所以按照教程我们有textview的更新方法,它将显示你的时间:
private void updateDisplay() {
mTimeDisplay.setText(
new StringBuilder()
.append(pad(mHour)).append(":")
.append(pad(mMinute)));
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
将为用户创建的对话框以选择时间:
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this,
mTimeSetListener, mHour, mMinute, false);
}
return null;
}
在这里,我将添加您想要的限制,即用户设置时间时的回调方法。您需要获取当前的小时和分钟,如果用户选择过去的时间,您不会显示他的更改并向他发送Toast或其他内容。
使用日历,您可以轻松获得它:
Calendar c = Calendar.getInstance();
// the callback received when the user "sets" the time in the dialog
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (mHour >= Integer.getInteger(c.get(Calendar.HOUR_OF_DAY)) && mMinute >= Integer.getInteger(c.get(Calendar.MINUTE))) {
mHour = hourOfDay;
mMinute = minute;
updateDisplay();
} else
//Display a toast or something to inform the user that he can't pick a past time.
}
现在,如果您希望用户无法在您创建的对话框中选择上一次,则必须创建自己的小时选择屏幕,因为TimePickerDialog对您可以选择的值没有限制。
希望它有所帮助!
答案 1 :(得分:0)
我修改了一些代码,它对我有用: 我已经在一个警告对话框中选择了日期和时间选择器,并在有人想通过其正面按钮设置警报时间时编写一些代码。
final DatePicker pickdate = (DatePicker) view
.findViewById(R.id.datePicker1);
final TimePicker pickTime = (TimePicker) view
.findViewById(R.id.timePicker1);
builder.setPositiveButton("Set Alarm Time",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int day = pickdate.getDayOfMonth();
int month = pickdate.getMonth();
int year = pickdate.getYear();
int hour = pickTime.getCurrentHour();
int min = pickTime.getCurrentMinute();
c = Calendar.getInstance();
if (min >= c.get(Calendar.MINUTE)
&& hour >= c.get(Calendar.HOUR_OF_DAY)
&& day >= c.get(Calendar.DAY_OF_MONTH)
&& (month + 1) >= c.get(Calendar.MONTH)
&& year >= c.get(Calendar.YEAR)) {
String setdate = year + "-" + (month + 1) + "-"
+ day + " " + hour + ":" + min;
//Use the string where you wants
}
else {
//show some error toast
Toast.makeText(context,
Html.fromHtml("<font color=RED><em><strong>Past Time Can't Be Added</strong></em>/font>")
,Toast.LENGTH_SHORT).show();
}
答案 2 :(得分:0)
if((hourOfDay <= (calendar.get(Calendar.HOUR_OF_DAY)))&&
(minute <= (calendar.get(Calendar.MINUTE)))){
Toast.makeText(getActivity(), "Wrong hour",
Toast.LENGTH_SHORT).show();
}