Android TimePicker AM/PM button not invoking onTimeChanged

前端 未结 11 1114
半阙折子戏
半阙折子戏 2021-02-05 12:38

I\'m having some issues implementing a TimePicker in my application that allows the user to change the time of a database record prior to inserting it.

The problem is th

11条回答
  •  隐瞒了意图╮
    2021-02-05 13:37

    I found this answer, but it didn't work for me, so I thought I would update.

    In 3.2 (and above?), the time picker does not have a button for am/pm. Instead it has a NumberPicker. The following code worked for me. The last bit is there because I needed to limit the time selected to no earlier than the 'min' date and no greater than the 'max' date, so I had to check the date selected in the matching DatePicker control:

            NumberPicker amPmView  = (NumberPicker)((ViewGroup)tp.getChildAt(0)).getChildAt(3);
            amPmView.setOnValueChangedListener(new OnValueChangeListener() { 
                @Override
                public void onValueChange(NumberPicker arg0, int arg1, int arg2) {
                    if(arg0.getValue()== 1){ 
                        if (tp.getCurrentHour() < 12)
                            tp.setCurrentHour(tp.getCurrentHour() + 12); 
                    } 
                    else{ 
                        if (tp.getCurrentHour() >= 12) 
                            tp.setCurrentHour(tp.getCurrentHour() - 12); 
                    } 
    
                    int year = dp.getYear();
                    int month = dp.getMonth();
                    int dayOfMonth = dp.getDayOfMonth();
                    int hourOfDay = tp.getCurrentHour();
                    int minute = tp.getCurrentMinute();
    
                    if (year == min.get(Calendar.YEAR) && month == min.get(Calendar.MONTH) && dayOfMonth == min.get(Calendar.DAY_OF_MONTH)){
                        if ((hourOfDay < min.get(Calendar.HOUR_OF_DAY))||
                            (hourOfDay == min.get(Calendar.HOUR_OF_DAY) && (minute < min.get(Calendar.MINUTE)))){
                            tp.setCurrentHour(min.get(Calendar.HOUR_OF_DAY));
                            tp.setCurrentMinute(min.get(Calendar.MINUTE));
                        }
                    }else if (year == max.get(Calendar.YEAR) && month == max.get(Calendar.MONTH) && dayOfMonth == max.get(Calendar.DAY_OF_MONTH)){
                        if ((hourOfDay > max.get(Calendar.HOUR_OF_DAY))||
                            (hourOfDay == max.get(Calendar.HOUR_OF_DAY) && (minute > max.get(Calendar.MINUTE)))){
                            tp.setCurrentHour(max.get(Calendar.HOUR_OF_DAY));
                            tp.setCurrentMinute(max.get(Calendar.MINUTE));
                        }
                    }
                } 
            }); 
    

提交回复
热议问题