MainActivity
public class MainActivity extends AppCompatActivity {
CalendarView cv_1;
DatePicker dp_1;
TimePicker tp_1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cv_1=(CalendarView)findViewById(R.id.cv_1);
cv_1.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
Toast.makeText(MainActivity.this, "选中的日期是:"+year+"-"+(month+1)+"-"+dayOfMonth, Toast.LENGTH_SHORT).show();
}
});
dp_1=(DatePicker)findViewById(R.id.dp_1);
//初始化日期选择器,并设置监听器
dp_1.init(2015, 0, 1, new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Toast.makeText(MainActivity.this, "选中的日期是:"+year+"-"+(monthOfYear+1)+"-"+dayOfMonth, Toast.LENGTH_SHORT).show();
}
});
tp_1=(TimePicker)findViewById(R.id.tp_1);
tp_1.setIs24HourView(true);//24小时制
tp_1.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
Toast.makeText(MainActivity.this, "选中的时间是:"+hourOfDay+":"+minute, Toast.LENGTH_SHORT).show();
}
});
}
}
View Code
actuvity_main
<?xml version="1.0" encoding="utf-8"?>View Code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.lenovo.textapp4.MainActivity"
android:orientation="vertical">
<CalendarView
android:layout_width="wrap_content"
android:layout_height="284dp"
android:firstDayOfWeek="1"
android:maxDate="12/31/2016"
android:minDate="01/01/2016"
android:id="@+id/cv_1"
android:visibility="gone">
</CalendarView>
<DatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:startYear="2010"
android:endYear="2018"
android:maxDate="10/1/2017"
android:minDate="02/01/2010"
android:id="@+id/dp_1">
<TimePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tp_1">
</TimePicker>
</DatePicker>
</LinearLayout>