CalendarView
, as you might have guessed, displays a calendar to the user,
designed to allow the user to pick a date.
You supply a starting date, which the user then manipulates, triggering
event listeners whenever the date is changed.
Note that this is a small calendar – it is not designed to show details within a date, such as appointments and times.
This view is available standalone and also as an optional adjunct to
the DatePicker
widget.
This view was added in API Level 11 and therefore will not be available on older versions of Android, though a backport is available that works on Android 2.2 onwards.
If you do nothing, the CalendarView
will start with today’s date,
though you can call a setDate()
method to pass in a Calendar
object
to use to change the initially-selected date. You can also call
setOnDateChangeListener()
to supply an OnDateChangeListener
to learn
when the user changes the date in the CalendarView
.
CalendarView
works well with Calendar
and GregorianCalendar
, in
terms of setting and getting the year/month/day-of-month from the
CalendarView
(as supplied to the onSelectedDayChange()
method of your
OnDateChangeListener
) and converting it into something you can use in your code.
The sample project can be found in
WidgetCatalog/CalendarView
.
Layout:
<CalendarView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/calendar"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Activity:
package com.commonsware.android.wc.calendar;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CalendarView;
import android.widget.CalendarView.OnDateChangeListener;
import android.widget.Toast;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class CalendarDemoActivity extends Activity implements
OnDateChangeListener {
CalendarView calendar=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
calendar=(CalendarView)findViewById(R.id.calendar);
calendar.setOnDateChangeListener(this);
}
@Override
public void onSelectedDayChange(CalendarView view, int year,
int monthOfYear, int dayOfMonth) {
Calendar then=new GregorianCalendar(year, monthOfYear, dayOfMonth);
Toast.makeText(this, then.getTime().toString(), Toast.LENGTH_LONG)
.show();
}
}
This is what a CalendarView
looks like in a few different Android
versions and configurations, based upon the sample app shown above.
Figure 1035: Android 4.0
Figure 1036: Android 4.1
Figure 1037: Android 5.0