Search code examples
androidtimepicker

Android - Disable (or Hide) Minute selection in TimePicker Dialog



In my project, I am using TimePicker dialog to allow users to select time. But I don't want them to select minutes. So, all I want is to disable (or hide) minute selection. So, How to do that?


Solution

  • I solved my problem by using Material TimePickerDialog Library.

    My solution:

    public class home extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener, ... {
        ...
        private EditText time;
        private TimePickerDialog timePickerDialog;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home);
            ...
    
            timePickerDialog = TimePickerDialog.newInstance(home.this, new Date().getHours(), new Date().getMinutes(), false);
            timePickerDialog.enableMinutes(false);
    
            time = (EditText) findViewById(R.id.time);
            time.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    timePickerDialog.show(getFragmentManager(), "TimePickerDialog");
                }
            });
        }
    
        @Override
        public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
            String form;
            if (hourOfDay > 12) {
                hourOfDay = hourOfDay - 12;
                form = "PM";
            } else {
                if (hourOfDay == 0) {
                    hourOfDay = 12;
                }
                form = "AM";
            }
            time.setText(String.valueOf(hourOfDay) + " " + form);
        }
    
        ...
    }