TimePickerDialog and TimePicker
onCreate(...) {
...
showDialog(TIME_DIALOG_ID);
timePicker = (TimePicker) findViewById(R.id.timePicker);
timePicker.setIs24HourView(true);
...
Button btnOpen = (Button) findViewById(R.id.btnSet);
btnOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(),
“Time selected:” +
timePicker.getCurrentHour().toString() +
“:” + timePicker.getCurrentMinute().toString(),
Toast.LENGTH_SHORT).show();
}
}
onCreateDialog(...) {
return new TimePi开发者_开发知识库ckerDialog(...)
}
Above is a code sample from an Android book. I was wondering how timePicker knows the current hour and current minute. timePicker is only defined in onCreate. When onCreateDialog is called with showDialog(), it returns a TimePickerDialog that in no way seems to know about timePicker, yet timePicker is able to get the current hour and minute to toast it.
TimePickerDialog contains a TimePicker widget which in turn implements code for getting the current time. The sample code is referencing the TimePicker in TimePickerDialog directly by assuming that TimePickerDialog will always contain a TimePicker with the id: timePicker
.
However, you don't need to magically know the id of the TimePicker. You can implement the TimePicker.OnTimeChangedListener callback interface which has access to the embedded TimePicker via the onTimeChanged (TimePicker view, int hourOfDay, int minute)
method as illustrated in this Time Picker tutorial instead.
When you call showDialog()
, the dialog is created in the Activity's View hierarchy. So when the next line does findViewById(R.id.timePicker)
, it finds the TimePicker
inside the dialog, presumably which has the id of timePicker
, and saves a reference to it in timePicker
.
On onCreate
Method you only have the reference.
when you click on btnOpen you call getCurrentHour()
and getCurrentMinute()
to get the current time.
精彩评论