我使用此指南创建了一个带有时间选择器的片段:
http://developer.android.com/guide/topics/ui/controls/pickers.html
现在我想将设置的时间发送回持有片段的活动。我搜索了如何做到这一点,我发现了这个:
http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
我试图在我的 Fragment 中创建一个 onTimeSet 接口,但由于我正在实现 TimePickerDialog.OnTimeSetListener,它要求我重写 onTimeSet 方法。我发现我可以简单地调用 getActivity() 发送数据,但我不确定这是否是一个好的选择,因为 android 开发页面建议使用接口方法。
我应该怎么办?
这是一些代码:
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// WHAT TO DO??
}
}
在我的活动中:
.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(CreateStopActivity.this.getSupportFragmentManager(), "timePicker");
}
});