Search code examples
androidandroid-custom-viewandroid-datepicker

Show TimePickerDialog or DatePicker in a custom view


Times ago I developed a custom datetime picker control. This custom picker control was developed by inheriting from LinearLayout class and has got some features like "declare-styleable" attributes to set properties at design-time, a set of Interfaces to simultate events and finally a large amount of code to play effects and manage date-time business logic.

Now my need is to show a DatePickerDialog and TimePickerDialog by pressing a button into my custom control. I searched on the android knowledge-base and the only method I found to show these dialogs is the Developer's DatePicker Guide.

Because of my control inherits directly from LinearLayout, I can't override onCreateDialog() method to provide the dialogs, simply because LinearLayout doesn't havethis method! How can I show these dialogs in my custom-control without any references to the parent activity? Pratically, I would like to have the opportunity to draw the control on many Activities as I can, without worrying about managing onCreateDialog() on each Activity, because the code that loads and launches the dialogs is defined once into my custom control (as you do in a simple .NET control when you have to show MessageBoxes [MessageBox.Show() doesn't require a Form instance])...

How can I achieve that? Thanks in advance...


Solution

  • Instead of using Activity.showDialog(), onCreateDialog(), etc; just use Dialog.show().

    Calendar calendar = Calendar.getInstance();
    mDialog = new DatePickerDialog(context, onDateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
    mDialog.show();
    

    Inside your button's onClickListener, you can modify mDialog anyway you want and then call mDialog.show().