To call it from a method, first you have to create the class that would generate the dialog.
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import java.util.Calendar;
public class DatePickerFragment extends DialogFragment {
private DatePickerDialog.OnDateSetListener listener;
public static DatePickerFragment newInstance(DatePickerDialog.OnDateSetListener listener) {
DatePickerFragment fragment = new DatePickerFragment();
fragment.setListener(listener);
return fragment;
}
public void setListener(DatePickerDialog.OnDateSetListener listener) {
this.listener = listener;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
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);
//Crea instancia de DatePickerDialog.
return new DatePickerDialog(getActivity(), listener, year, month, day);
}
}
Actually the method would show the Dialog and the only way to obtain the date is when the user selects it, for this it creates a variable where the date will be obtained when it is selected in the dialog:
private String fechaSeleccionada;
this would be the method:
private void crearDialogoFecha(){
DatePickerFragment newFragment = DatePickerFragment.newInstance(new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
fechaSeleccionada = day + " / " + (month + 1 /* because moth starts with 0*/) + " / " + year;
Log.i(TAG, "La fecha seleccionada es: " + fechaSeleccionada);
}
});
newFragment.show(getSupportFragmentManager(), "datePicker");
}