定义布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorGray"
android:orientation="vertical"
>
<TextView
android:id="@+id/selectDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/selectDate"
/>
<CalendarView
android:id="@+id/calendarView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:firstDayOfWeek="1"
android:shownWeekCount="5"
android:selectedWeekBackgroundColor="@color/colorPrimaryDark"
android:focusedMonthDateColor="@color/colorAccent"
android:weekSeparatorLineColor="@color/colorPrimary"
android:unfocusedMonthDateColor="#F9F"
/>
</LinearLayout>
主程序文件代码:
package com.toby.personal.testlistview;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.widget.CalendarView;
import android.widget.TextView;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
final private static String TAG = "Toby_Test";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CalendarView calendarView = (CalendarView) findViewById(R.id.calendarView);
final TextView selectData = (TextView) findViewById(R.id.selectDate);
final Calendar c = Calendar.getInstance();
selectData.setText(getText(R.string.selectDate) + " " +
String.valueOf(c.get(Calendar.YEAR)) + "/" +
String.valueOf(c.get(Calendar.MONTH)) + "/" +
String.valueOf(c.get(Calendar.DATE)));
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(@NonNull CalendarView calendarView,
int year, int month, int dayOfMonth) {
selectData.setText(getText(R.string.selectDate) + " " + String.valueOf(year) + "/" +
String.valueOf(month) + "/" + String.valueOf(dayOfMonth));
}
});
}
}
本示例的运行效果:
参考文献:《疯狂Android讲义(第2版)》