Search code examples
androidtimepicker

TimePicker on EditText click


How to set a Timepicker on EditText Click in android.

I have searched the following links but it doesn't work as the showDialog() is now depricated.

TimePicker Dialog from clicking EditText

http://www.botskool.com/geeks/how-create-time-picker-dialog-selecting-time-android

any help would be acknowledge.


Solution

  • I got the answer for the same:-

    Include the following methods in your Fragment.

    public void selectTimeToDisplay(EditText edText) {
            DialogFragment dialogFragment = new DisplayTimeFragment(edText);
            dialogFragment.show(getActivity().getSupportFragmentManager(), "DatePicker");
        }
    
    public void setSelectedTime(String hourOfDay,String minute, EditText edText) {
        edText.setText(hourOfDay + ":" + minute);
    }
    

    Define DisplayTimeFragment as a Inner class in your Fragment:-

    public class DisplayTimeFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
            EditText edText;
            public DisplayTimeFragment(EditText edText){
                this.edText = edText;
            }
    
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                // Use the current time as the default values for the picker
                final Calendar c = Calendar.getInstance();
                int hour = c.get(Calendar.HOUR_OF_DAY);
                int minute = c.get(Calendar.MINUTE);
                return new TimePickerDialog(getActivity(), this, hour, minute,
                        DateFormat.is24HourFormat(getActivity()));
            }
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                String sHrs, sMins;
                if(minute<10){
                    sMins = "0"+minute;
                }else{
                    sMins = String.valueOf(minute);
                }
                if(hourOfDay<10){
                    sHrs = "0"+hourOfDay;
                }else{
                    sHrs = String.valueOf(hourOfDay);
                }
                setSelectedTime(sHrs,sMins, edText);
    
            }
        }
    

    Now, Write the following code in the onClickListener of your Edittext.

    as,

    edStartTime.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    selectTimeToDisplay(edStartTime);
                }
            });
    

    Note:- For Smooth functioning, Set focusable to false in the xml of the Edittext.

    Bingo.. It will work as charms for any no of EditText now...