Search code examples
androidtimewidgetpickertimepicker

How can I add new button in date picker widget in android?


I want to add new button,which is clear button, to date picker widget and time picker widget in my android application. In default, these widgets have two button,set and cancel. How can I add one more button to these two button

Is it possible? If yes, can you give some example?

Thanks


Solution

  • This is how I implemented the "Clear" button in my app. When the user clicks Clear, the year/month/day values are all 0. You can use onDateSet() in your app for both the Set button and Clear button this way.

    I referenced the Android source code (\frameworks\base\core\java\android\app\DatePickerDialog.java).

    I also used the help of esilver.

    public class DatePickerDialogPlus extends DatePickerDialog {
        private final DatePicker mDatePicker;
        private final OnDateSetListener mCallBack;
    
        /**
         * @param context The context the dialog is to run in.
         * @param callBack How the parent is notified that the date is set.
         * @param year The initial year of the dialog.
         * @param monthOfYear The initial month of the dialog.
         * @param dayOfMonth The initial day of the dialog.
         */
        public DatePickerDialogPlus(Context context, OnDateSetListener callBack, 
                int year, int monthOfYear, int dayOfMonth) {
            super(context, 0, callBack, year, monthOfYear, dayOfMonth);
    
            mCallBack = callBack;
    
            Context themeContext = getContext();
            setButton(BUTTON_POSITIVE, 
                themeContext.getText(R.string.datePicker_setButton), this);
            setButton(BUTTON_NEUTRAL, 
                themeContext.getText(R.string.datePicker_clearButton), this);
            setButton(BUTTON_NEGATIVE, 
                themeContext.getText(R.string.datePicker_cancelButton), null);
            setIcon(0);
            setTitle(R.string.datePicker_title);
    
            LayoutInflater inflater = (LayoutInflater) 
                themeContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.date_picker_dialog, null);
            setView(view);
            mDatePicker = (DatePicker) view.findViewById(R.id.datePicker);
            mDatePicker.init(year, monthOfYear, dayOfMonth, this);
        }
    
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (mCallBack != null) {
                if (which == BUTTON_POSITIVE) {
                    mDatePicker.clearFocus();
                    mCallBack.onDateSet(mDatePicker, mDatePicker.getYear(), 
                        mDatePicker.getMonth(), mDatePicker.getDayOfMonth());
                } else if (which == BUTTON_NEUTRAL) {
                    mDatePicker.clearFocus();
                    mCallBack.onDateSet(mDatePicker, 0, 0, 0);
                }
            }
        }
    }