日历视图(CalendarView)可用于显示和选择日期,用户既可选择一个日期,也可通过触摸来滚动日历。如果希望监控该组件的日历改变,可调用CalendarView的setOnDateChangeListener()方法为此组件的点击事件添加事件监听器。
下面通过实例来示范CalendarView组件的功能与用法。
实例:选择您的生日
布局文件如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="选择您的生日:"/>
<!-- 设置以星期二为每周第一天
设置该组件总共显示4个星期
并对该组件日期时间进行了定制 -->
<CalendarView android:layout_width="match_parent"
android:layout_height="match_parent"
android:firstDayOfWeek="3"
android:shownWeekCount="4"
android:selectedWeekBackgroundColor="#aff"
android:focusedMonthDateColor="#f00"
android:weekSeparatorLineColor="#ff0"
android:unfocusedMonthDateColor="#f9f"
android:id="@+id/calenddarView"/>
</LinearLayout>
上面的布局文件中粗体字代码定义了一个CalendarView组件,并设置该组件总共只显示4周,以每周的星期二作为第一天。
为了监听用户选择日期的事件,本实例在Activity代码中调用该组件的setOnDateChangeListener()方法来添加事件监听器。该实例的Activity代码如下。
package org.crazyit.helloworld;import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.CalendarView;
import android.widget.CalendarView.OnDateChangeListener;
import android.widget.Toast;public class CalendarViewTest extends Activity { CalendarView cv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar_view_test);
cv=(CalendarView)findViewById(R.id.calenddarView);
//为CalendarView组件的日期改变事件添加事件监听器
cv.setOnDateChangeListener(new OnDateChangeListener(){ @Override
public void onSelectedDayChange(CalendarView view, int year,
int month, int dayOfMonth) {
// TODO Auto-generated method stub
//使用Toast显示用户选择的日期
Toast.makeText(CalendarViewTest.this,
"你生日是"+year+"年"+month+"月"+dayOfMonth+"日"
, Toast.LENGTH_SHORT).show();
} });
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.calendar_view_test, menu);
return true;
}}
运行该Activity出现下图所示效果: