I have a working TimePickerFragment which uses the current time as the default values for the picker. Now I want to pass the old selected value for minute and hour to show in the picker. How can I do that?
This is the code:
Activity:
TimePickerFragment newFragmentNight = TimePickerFragment.newInstance(TO_TIME_PICKER_ID);
newFragmentNight.show(getSupportFragmentManager(), "timePicker");
DialogFragment:
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener
{
private int mId;
private TimePickedListener mListener;
static TimePickerFragment newInstance(int id) {
Bundle args = new Bundle();
args.putInt("picker_id", id);
TimePickerFragment fragment = new TimePickerFragment();
fragment.setArguments(args);
return fragment;
}
public Dialog onCreateDialog(Bundle savedInstanceState)
{
// here I don't want to use the current time, I want to use the time passing from the activity
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
mId = getArguments().getInt("picker_id");
// create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
Try just adding new values to the newInstance()
static method and bundle it that way. It can pass on the information just the same as you would with a constructor. Try the following:
static TimePickerFragment newInstance(int id, int hour, int minute)
{
Bundle args = new Bundle();
args.putInt("picker_id", id);
args.putInt("hour", hour);
args.putInt("minute", minute);
TimePickerFragment fragment = new TimePickerFragment();
fragment.setArguments(args);
return fragment;
}
public Dialog onCreateDialog(Bundle savedInstanceState)
{
Bundle args = getArguments();
final Calendar c = Calendar.getInstance();
//The second input is a default value in case hour or minute are empty
int hour = args.getInt("hour", c.get(Calendar.HOUR_OF_DAY));
int minute = args.getInt("minute", c.get(Calendar.MINUTE));
mId = getArguments().getInt("picker_id");
// create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
Hope this helps. Good luck!