Android:将Time Picker Fragment数据发送到Activity

时间:2013-02-07 12:11:25

标签: android fragment timepicker

我使用此指南创建了一个带有时间选择器的片段:

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");
        }

    });

2 个答案:

答案 0 :(得分:1)

你可以用构造函数传递它。

    Button timeBtn;

    public TimePickerFragment(Button btn) {
        timeBtn = btn;
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        timeBtn.setText(hourOfDay + ":" + minute);
    }

答案 1 :(得分:0)

我认为你应该在你的活动中实现TimePickerDialog.OnTimeSetListener接口。在哪里创建TimePickerFragment。像这样的Smth:

public class YourActivity extends FragmentActivity implements TimePickerDialog.OnTimeSetListener {
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        // DO HERE ANYTHING WITH DATA
    }
}

并且不要忘记在构造函数中将您的活动作为OnTimeSetListener传输。

dialog = new TimePickerDialog(yourContext, yourActivity, hourOfDay, minute, is24HourView);

观看TimePickerDialog了解更多信息