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 TimePickerDialog(...)
}


上面是一本Android书中的代码示例。我想知道timePicker如何知道当前小时和当前分钟。 timePicker仅在onCreate中定义。当用showDialog()调用onCreateDialog时,它返回一个TimePickerDialog,它似乎根本不了解timePicker,但是timePicker能够获取当前的时分。

最佳答案

TimePickerDialog包含一个TimePicker小部件,该小部件又实现了用于获取当前时间的代码。示例代码通过假设TimePicker始终包含ID为timePickerTimePickerDialog来直接引用TimePickerDialog中的TimePicker

但是,您无需神​​奇地知道TimePicker的ID。您可以实现TimePicker.OnTimeChangedListener回调接口,该接口可以通过onTimeChanged (TimePicker view, int hourOfDay, int minute)方法访问嵌入式TimePicker,如本Time Picker tutorial所示。

关于android - TimePickerDialog和TimePicker,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7325039/

10-12 06:08