Skip to main content

DatePickers in Android

DatePicker is a view which lets the user select a date showing a calendar or 3 spinners for dd, mm and yy.

Let us see how to use this.

Easy Method:

To use a DatePicker you can use DatePickerDialog. This can be created and shown programmatically too.


public void onCreate(Bundle b){ 
/*********/
Button btn = (Button)findViewById(R.id.btn);
 btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPickerDialog();
            }
        });
}

 private void showPickerDialog() {
       
        DatePickerDialog  dtPickerDlg =  new DatePickerDialog(this, this, 2017, 10, 20);
        dtPickerDialog.show();
}
        
 


In our xml file, let us have a button and in the onclick listener of the button, let us display the date picker dialog - we call showPickerDialog.

In showPickerDialog,  we are using a random date to initialize.

The first  parameter is the context. Second parameter is the class which implements the interface OnDateSetListener. Next three parameters are year, month (Jan is 0) and day of month.

Let us make our activity implement this interface

public class SomeActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener{

@Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.DAY_OF_MONTH,dayOfMonth);
        c.set(Calendar.MONTH,month);
        c.set(Calendar.YEAR,year);
        mDate = DateFormat.format("dd-MM-yyyy",c).toString();
        TextView tvMessage = (TextView)findViewById(R.id.textView);
        tvMessage.setText("You have selected :"+mDate);

    }

As we can see, we modified the class header added to the phrase "implements DatePickerDialog.OnDateSetListener " to it.

The studio will prompt you to add the method onDateSet. The last 3 parameters are selected year, month and day of the Datepicker.

In this example, I am displaying this value in a textview.

Calendar.getInstance() will return  a calendar object with current date and time. You can modify it as shown by setting day, month and year fields.


Note that we initialized the dialog with 2017,10,20 and the dialog shows 2017 November 20th. So keep in mind, month number starts with 0. 

There is a GOTCHA

Now let us try to display the date picker as a 3 spinners. This can be done using two lines of code


dtPickerDlg.getDatePicker().setSpinnersShown(true);  
 dtPickerDlg.getDatePicker().setCalendarViewShown(false);

Studio gives you a warning that these methods are deprecated. But unlike other deprecated methods, these methods actually do not work in sdk 21- Lollipop onwards. So the dialog still shows calendar instead of spinners.

Solution

I tried various options. As far as I could find out, the only solution seems to be to use DatePicker in a normal dialog or a dialog fragment instead of a DatePickerDialog.

Let us look at that.


final Dialog  dtPickerDlg = new Dialog(this);        
       dtPickerDlg.setContentView(R.layout.picker);     
        final DatePicker picker =(DatePicker) dtPickerDlg.findViewById(R.id.datePicker);
        Button btnOk =(Button) dtPickerDlg.findViewById(R.id.okbutton);
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dtPickerDlg.dismiss();
            }
        });
        Calendar c = Calendar.getInstance();
        int dd = c.get(Calendar.DAY_OF_MONTH);
        int mm = c.get(Calendar.MONTH);
        int yy = c.get(Calendar.YEAR);
        picker.init(yy,mm,dd,this);//last parameter is datechangelistener
        dtPickerDlg.show();
        dtPickerDlg.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {

                TextView tvMessage = (TextView)findViewById(R.id.textView);
                tvMessage.setText("You have selected :"+mDate);
            }
        });

Here is the layout xml file /res/layout/picker.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <DatePicker
        android:id="@+id/datePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:calendarViewShown="false"
        android:datePickerMode="spinner" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:background="@android:color/transparent"
        android:text="OK"
        android:id="@+id/okbutton"/>
</LinearLayout>

Look at the two highlighted lines. You can set datePickerMode to spinner or calendar. Even when you set to spinner, a calendar is also shown. To avoid that, set  calendarviewshown as false.

Now for the listeners! Funny, there is no dateset listener. Not so easily found at least.

I tried documentation and trying to use autocomplete with setOnDateSet or addOnDateSet etc. No. They are not to be found.

Finally the solution was found as init method. Datepicker should have an init method with initial values of dd, mm and yy and also the datesetlistener.

Look at the pink highlighted line again.

  picker.init(yy,mm,dd,this);//last parameter is datechangelistener


The init method takes OnDateChangeListener as fourth parameter. By adding this as fourth parameter, your activity should implement
DatePicker.OnDateChangedListener  

Studio adds the interface and the method like this.


public class SomeActivity extends AppCompatActivity implements DatePicker.OnDateChangedListener{
 


@Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        Calendar c = Calendar.getInstance();
        c.set(year,monthOfYear,dayOfMonth);
        mDate = DateFormat.format("dd-MM-yyyy",c).toString();
    } 
 
} 

So that's it. Mission accomplished. We are able to show a date selector as a spinner.


You can download the complete project from here

Comments

  1. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
    Android Training in chennai | Best Android Training in chennai|Android Training in chennai with placement | Android Training

    ReplyDelete

Post a Comment

Popular posts from this blog

Simple ListView Adapter and list item select

When you are using a listview in your applications many a times you will write your own adapter to display item. But if your list is very simple showing a list of strings, you can use inbuilt adapters like ArrayAdapter, SimpleCursorAdapter etc.

ArrayAdapterLet us look at an example

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ListView android:layout_height="wrap_content" android:id="@+id/listView1" android:layout_width="match_parent" android:layout_margin="20dp"> </ListView> </LinearLayout>

And add these lines to the onCreate method of the activity.

super.onCreate(savedInstanceState); …

Drawables in Android - Layer drawable

Let us see how to use layer drawable. You can have two or more bitmaps on different layers to create such a drawable

Using xml:

You should use layer-list in your xml file to create layerdrawable. Here is layer.xml
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <bitmap android:src="@drawable/whiteicon" android:gravity="top|left"/> </item> <item> <bitmap android:src="@drawable/blueicon" android:gravity="top|left"/> </item> <item> <bitmap android:src="@drawable/redicon" android:gravity="top|left"/> </item> </layer-list>
We are using three different bitmaps whiteicon.png, redicon.png and blueicon.png which are present in /res/drawable/mdpi folder. All these are of different sizes and aligned to top left. This drawab…