有没有办法在TimePickerDialog中以编程方式将am更改为pm?

时间:2011-03-05 16:34:45

标签: android datetimepicker timepicker

我正在寻找一种方法来动态更改我的Android应用程序的TimePickerDialog中的AM / PM,同时使用12小时格式。我希望在对话框中的小时从11变为12但在用户点击设置按钮之前,将AM切换到PM并反之亦然。这是可能的还是我需要研究创建一个自定义的TimePickerDialog控件?我目前的代码如下。谢谢你的帮助!

    // Start Time
    starttime = (Button)findViewById(R.id.starttime); 

    starttime.setOnClickListener(new View.OnClickListener() { 
        public void onClick(View v) { 
            boolean is24HourFormat = use24HourFormat();
            new TimePickerDialog(DutyHoursForm.this, 
                    startTimeListener, 
                    startDateAndTime.get(Calendar.HOUR_OF_DAY), 
                    startDateAndTime.get(Calendar.MINUTE), 
                    is24HourFormat).show(); 
            } 
    }); 

TimePickerDialog.OnTimeSetListener startTimeListener = new TimePickerDialog.OnTimeSetListener() { 
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) { 
        startDateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay); 
        startDateAndTime.set(Calendar.MINUTE, minute); 
        updateStartTime(); 
    } 
};

1 个答案:

答案 0 :(得分:1)

初始化变量以跟踪更改前的小时 - 例如lastCurrentHour 然后你可以在onTimeChanged中执行此操作:

public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
    if(DateFormat.is24HourFormat(this)) return;

    if(lastCurrentHour == 0 && view.getCurrentHour()==11 ){
        view.setCurrentHour(23);
    }else

    if(lastCurrentHour == 11 && view.getCurrentHour()==0 ){
        view.setCurrentHour(12);
    }else

    if(lastCurrentHour == 12 && view.getCurrentHour()==23 ){
        view.setCurrentHour(11);
    }else

    if(lastCurrentHour == 23 && view.getCurrentHour()==12 ){
        view.setCurrentHour(0);
    }
    lastCurrentHour = view.getCurrentHour();
}

找一个有效的例子here