You should note that this Dialog is a Fragment.
That said, the main idea will be this:
When you need to launch this Date Picker, then you will show that fragment as an overlay of the current activity. This fragment has a date picked listener: an event that is launched when the user picks a date. Ok, everything easy until here. The hardest thing to understand will be the last one: Interaction between the fragment and the activity. What for? Because the Activity needs to know whick Date was selected. To achieve this the Fragment will have a public Interface that will be implemented by the activity.
Ok, let's see the code:
MyActivity.java
public class MyActivity extends FragmentActivity implements DatePickerFragment.FragmentInteraction{
@Override
public void onCreate(Bundle savedInstanceState){
Button showDatePickerButton = (Button)findViewById(R.id.dateButton);
showDatePickerButtonsetOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), getString(R.string.datePickerTitle));
}
});
}
@Override
public void doSomethingWithDate(int day, int month, int year) {
Log.d("", "SELECTED DATE " + month + "/" + day + "/" + year);
}
}
DatePickerFragment.java
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
private FragmentInteraction mListener;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mListener = (FragmentInteraction) activity;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Show picker with actual date presetted
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 anio, int mes, int dia) {
mListener.doSomethingWithDate(dia, mes + 1, anio);
}
public interface FragmentInteraction{
public void doSomethingWithDate(int dia, int mes, int anio);
}
}