Following the official doc http://developer.android.com/guide/topics/ui/controls/pickers.html#DatePicker.
I have used just the same code, and added only the result formatting in the onDateSet
method:
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
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);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar c = Calendar.getInstance();
c.set(year, month, day);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(c.getTime());
// How to get the string from here to the caller?
}
}
For testing, the caller activity just displays the TextView
and calls the picker when the user touches the widget:
public class OrderHeadEditActivity extends Activity {
private TextView mDTDelivery;
...
@Override
protected void onCreate(Bundle bundle) {
...
mDTDelivery = (TextView) findViewById(R.id.order_head_view_dt_delivery);
...
mDTDelivery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment picker = new DatePickerFragment();
picker.show(getFragmentManager(), "datePicker");
}
});
}
...
}
The date picker is displayed, and after setting the breakpoint at the place where the result is formatted to a string, I can see it works.
However, I do not know how to pass the string value back to the mtDTDelivery
widget?