TimePicker来展示时分秒
DatePicker来展示年月日
代码实现
- 页面布局的实现
<?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:orientation="vertical"
>
<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
- 功能的实现
datePicker=(DatePicker) findViewById(R.id.datePicker);
timePicker=(TimePicker) findViewById(R.id.timePicker);
//获取一个日历对象
calendar=Calendar.getInstance();
//获取年月日时分秒的信息
year=calendar.get(Calendar.YEAR);
// //它是从零开始计月份的
month=calendar.get(Calendar.MONTH)+1;
day=calendar.get(Calendar.DAY_OF_MONTH);
hour=calendar.get(Calendar.HOUR_OF_DAY);
minute=calendar.get(Calendar.MINUTE);
setTitle(year+":"+month+":"+day+":"+hour+":"+minute);
对时间的设置进行初始化 使用OnDateChangedListener来监听时间的变化进行显示
//初始化操作
datePicker.init(year, calendar.get(Calendar.MONTH), day, new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
setTitle(year+":"+(monthOfYear+1)+":"+dayOfMonth);
}
});
对时分秒的设置进行初始化 使用OnTimeChangedListener来监听时间的变化进行显示
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
setTitle(hourOfDay+":"+minute);
}
});
我们一对话框的形式
*展示时间 使用 OnDateSetListener来监听时间的变化进行显示
new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
setTitle(year+":"+month+":"+dayOfMonth);
}
},year,calendar.get(Calendar.MINUTE),day).show();
*展示时分 使用 OnTimeSetListener来监听时间的变化进行显示
//以对话框的形式展示时分秒
new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
setTitle(hourOfDay+":"+minute);
}
},hour,minute,true).show();