public
Last active

There is a bug in Android's TimePicker for 4.0+. The onTimeChanged() callback in the onTimeChangedListener() is not called when the user changes am/pm. This sample code shows a workaround for the Android TimePicker in 4.0+, demonstrating a TextView that is always in sync with the TimePicker, regardless of which vertical spinner is being manipulated by the user. Here are the two reported bug-report issues given to Google: https://code.google.com/p/android/issues/detail?id=24388 and https://code.google.com/p/android/issues/detail?id=18982

  • Download Gist
ActivityMain.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
// This is for API 15-17+
// Tested on 4.0.3
public class ActivityMain extends Activity {
ImageButton buttonTimeDone;
NumberPicker numberPickerAmPm;
TextView textViewTime;
TimePicker timePickerMain;
 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupViews();
setupTimePickerListener();
}
private void setupViews() {
buttonTimeDone = (ImageButton) findViewById(R.id.buttonTimeDone);
textViewTime = (TextView) findViewById(R.id.textViewTime);
timePickerMain = (TimePicker) findViewById(R.id.timePickerMain);
}
private void setupTimePickerListener() {
timePickerMain.setIs24HourView(DateFormat.is24HourFormat(this));
timePickerMain.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
if (DateFormat.is24HourFormat(ActivityMain.this)) {
textViewTime.setText("At: " + hourOfDay + ":" + minute);
} else {
if (hourOfDay == 0) { hourOfDay = 12; }
textViewTime.setText("At: " + ((hourOfDay > 12)?hourOfDay-12:hourOfDay) + ":" + ((minute < 10)?"0":"") + minute + ((numberPickerAmPm.getValue() == 0)?" am":" pm"));
}
}
});
numberPickerAmPm = (NumberPicker)((ViewGroup) timePickerMain.getChildAt(0)).getChildAt(3);
numberPickerAmPm.setOnValueChangedListener(new OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int hourOfDay = (timePickerMain.getCurrentHour() + 12) % 24;
int minute = timePickerMain.getCurrentMinute();
timePickerMain.setCurrentHour(hourOfDay);
if (hourOfDay == 0) { hourOfDay = 12; }
if (picker.getValue() == 0) {
textViewTime.setText("At: " + ((hourOfDay > 12)?hourOfDay-12:hourOfDay) + ":" + ((minute < 10)?"0":"") + minute + " am");
} else {
textViewTime.setText("At: " + ((hourOfDay > 12)?hourOfDay-12:hourOfDay) + ":" + ((minute < 10)?"0":"") + minute + " pm");
}
}
});
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.