Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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 manipula…
// 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");
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.