Search code examples
androidandroid-fragmentsdialogtimepicker

How to use time picker dialog when the main class extends a fragment on its own?


I can't understand how to use time picker dialog when my main class is a fragment on its own.

Please share some code so that I can solve this problem. I am stuck with this. Are there some additional methods that I would require to implement?

Using a separate TimePickerFragment class public class FirstFragment extends Fragment implements TimePickerFragment.TimeDialogListener throws the error: Class 'FirstFragment' must either be declared abstract or implement abstract method 'onFinishDialog(String)' in 'TimeDialogListener'


Solution

  • Class 'FirstFragment' must either be declared abstract or implement abstract method 'onFinishDialog(String)' in 'TimeDialogListener'

    This error indicate that you need to override the method onFinishDialog(String cause its declared as abstract in TimeDialogListener. Just override it in your class.

    @Override
    public void onFinishDialog(String s){
    
    }
    

    Apart from that you can directly use TimePickerDialog in your class as.

    private void showTimePicker(){
        Calendar calendar =Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        TimePickerDialog timePicker = new TimePickerDialog(context, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                //Do the stuff here
            }
        }, hour, minute, false);
        timePicker.setTitle("Pick Time");
        timePicker.show();
    }