The Most Efficient Way To Create A DatePickerDialog

1

Which is the most efficient way and with less amount of code to create a DatePickerDialog type object and that returns the date but implemented for a function

String CrearDialogoFecha()
{
 //Aqui el objeto tipo DatePickerDialog
  DatePickerDialog dialogo;

 //Fecha Ingresada 
 String Fecha = "Fecha Ingresada";

  //Devolver la fecha
 Return Fecha;
}
    
asked by Diego 17.05.2018 в 03:01
source

1 answer

-1

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");
}

    
answered by 18.05.2018 в 20:03