Skip to content

Instantly share code, notes, and snippets.

@blehr
Last active August 19, 2018 20:24
Show Gist options
  • Save blehr/b27c043858044749f07e4f1b52a3161f to your computer and use it in GitHub Desktop.
Save blehr/b27c043858044749f07e4f1b52a3161f to your computer and use it in GitHub Desktop.
DatePickerFragment sending results to initiating fragment
public class DatePickerFragment extends AppCompatDialogFragment implements DatePickerDialog.OnDateSetListener {
private static final String TAG = "DatePickerFragment";
final Calendar c = Calendar.getInstance();
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Set the current date as the default date
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Return a new instance of DatePickerDialog
return new DatePickerDialog(getActivity(), DatePickerFragment.this, year, month, day);
}
// called when a date has been selected
public void onDateSet(DatePicker view, int year, int month, int day) {
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
String selectedDate = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).format(c.getTime());
Log.d(TAG, "onDateSet: " + selectedDate);
// send date back to the target fragment
getTargetFragment().onActivityResult(
getTargetRequestCode(),
Activity.RESULT_OK,
new Intent().putExtra("selectedDate", selectedDate)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment