How do I get TimePickerDialog to start with the current time?

3

I made TimePickerDialog , but I can not get it to call the current time at the beginning, it always calls 00h00. I wonder where I'm going wrong.

Code:

private void chamarTimePickerDialog() {
    TimePickerDialog.OnTimeSetListener  mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hora, int minuto) {
            Toast.makeText(getActivity(), hora+ ":" + minuto, Toast.LENGTH_SHORT).show();
            capHora.setText(hora+ ":" +minuto);


            Calendar calNow = Calendar.getInstance();
            calNow.setTimeInMillis(System.currentTimeMillis());
            calNow.set(Calendar.HOUR_OF_DAY, hora);
            calNow.set(Calendar.MINUTE, minuto);

        }
    };
    TimePickerDialog dialog = new TimePickerDialog(getActivity(), mTimeSetListener,0, 0, true);

    dialog.show();
}
    
asked by anonymous 02.11.2016 / 03:53

1 answer

4

You can enter the starting hour and minute at the time of object construction TimePickerDialog .

See the builder :

TimePickerDialog (Context context, 
                TimePickerDialog.OnTimeSetListener listener, 
                int hourOfDay, 
                int minute, 
                boolean is24HourView)

hourOfDay and minute are the time and minutes with which the TimePickerDialog is initialized.

You are passing zero to each of these parameters,

TimePickerDialog dialog = new TimePickerDialog(getActivity(), mTimeSetListener,0, 0, true);

then be initialized with 00h00

Change the code to look like this:

private void chamarTimePickerDialog() {
    TimePickerDialog.OnTimeSetListener  mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hora, int minuto) {
            Toast.makeText(getActivity(), hora+ ":" + minuto, Toast.LENGTH_SHORT).show();
            capHora.setText(hora+ ":" +minuto);


            Calendar calNow = Calendar.getInstance();
            //Não é necessário, getInstance já retorna o calendário com a data e hora actual
            //calNow.setTimeInMillis(System.currentTimeMillis());
            calNow.set(Calendar.HOUR_OF_DAY, hora);
            calNow.set(Calendar.MINUTE, minuto);

        }
    };

    //Cria um calendário com a data e hora actual
    Calendar calNow = Calendar.getInstance();
    TimePickerDialog dialog = new TimePickerDialog(getActivity(),
                                                   mTimeSetListener, 
                                                   Calendar.HOUR_OF_DAY,
                                                   Calendar.MINUTE,
                                                   true);

    dialog.show();
}
    
02.11.2016 / 13:05