Put the current date by Default in the calendar

2

I have made a method that allows me to choose the date of a calendar that is shown and paste the selection in an EditText, but what I want is that by default the date of the current day appears in the EditText, without having to be selecting the year, month and day of the calendar. thanks.

Here I leave the code that implemente selecting year, month and day.

 public void metodo_fecha(View v){
    final Calendar c =Calendar.getInstance();
    dia=c.get(Calendar.DAY_OF_MONTH);
    mes=c.get(Calendar.MONTH);
    ano=c.get(Calendar.YEAR);

    DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            etfecha.setText(dayOfMonth+"/"+(month+1)+"/"+year);
        }
    },dia,mes,ano);
    datePickerDialog.show();

}
    
asked by Pedro Narrea 21.12.2018 в 17:24
source

1 answer

0

Your error is because to correctly initialize the DatePickerDialog you must use year, month and day, NO day, month, year.

DatePickerDialog (Context context,                 int themeResId,                 DatePickerDialog.OnDateSetListener listener,                 int year,                 int monthOfYear,                 int dayOfMonth)

should be:

DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        etfecha.setText(dayOfMonth+"/"+(month+1)+"/"+year);
    }
}, ano, mes, dia /*dia,mes,ano*/);

you have to initialize it correctly with the year, month and day data that you get from the calendar.

public void metodo_fecha(View v){
    final Calendar c =Calendar.getInstance();
    dia=c.get(Calendar.DAY_OF_MONTH);
    mes=c.get(Calendar.MONTH);
    ano=c.get(Calendar.YEAR);

    DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            etfecha.setText(dayOfMonth+"/"+(month+1)+"/"+year);
        }
    },ano,mes,dia);
    datePickerDialog.show();

}

    
answered by 21.12.2018 / 17:47
source