Last active
April 9, 2016 18:38
-
-
Save danialgoodwin/5694256 to your computer and use it in GitHub Desktop.
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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
this is not working with me on Android 6