PX Developer
PX Developer

Reputation: 8145

Android: send Time Picker Fragment data to Activity

I created a fragment with a time picker with this guidance:

http://developer.android.com/guide/topics/ui/controls/pickers.html

Now I want to send the set time back to the activity holding the fragment. I searched how to do it and I found this:

http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity

I tried to create an interface of onTimeSet in my Fragment, but since I'm implementing TimePickerDialog.OnTimeSetListener it requests me to override the onTimeSet method. I found I can send the data simply calling getActivity(), but I'm not sure if that's a good option since the android development page recomends using the interface method.

What should I do?

Here's some code:

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??
}


}

In my activity:

.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            DialogFragment newFragment = new TimePickerFragment();
            newFragment.show(CreateStopActivity.this.getSupportFragmentManager(), "timePicker");
        }

    });

Upvotes: 3

Views: 5011

Answers (2)

grine4ka
grine4ka

Reputation: 2938

I think you should implement TimePickerDialog.OnTimeSetListener interface in your activity. where you create TimePickerFragment. Smth like this:

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

and don't forget to transmit yout activity as OnTimeSetListener in constructor.

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

watch TimePickerDialog for more information

Upvotes: 0

DoronK
DoronK

Reputation: 4837

you can pass it with constructor.

    Button timeBtn;

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

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

Upvotes: 1

Related Questions