时钟AnalogClock与DigitalClock

1. 获得当前年月日时分

1         Calendar cal = Calendar.getInstance();
2         year = cal.get(Calendar.YEAR);
3         month = cal.get(Calendar.MONTH);
4         day = cal.get(Calendar.DAY_OF_MONTH);
5         hour = cal.get(Calendar.HOUR);
6         minute = cal.get(Calendar.MINUTE);


2.初始化DatePicker组件,指定监听

 1         // 初始化datepicker组件,指定监听
 2         datePic.init(year, month, day, new OnDateChangedListener() {
 3 
 4             @Override
 5             public void onDateChanged(DatePicker view, int year,
 6                     int monthOfYear, int dayOfMonth) {
 7                 // TODO Auto-generated method stub
 8                 AndroidAnalogClockActivity.this.year = year;
 9                 AndroidAnalogClockActivity.this.month = monthOfYear;
10                 AndroidAnalogClockActivity.this.day = dayOfMonth;
11                 showDate(year, monthOfYear, dayOfMonth, hour, minute);
12             }
13         });

3.指定TimePicker监听

 1         timePic.setOnTimeChangedListener(new OnTimeChangedListener() {
 2             
 3             @Override
 4             public void onTimeChanged(TimePicker arg0, int hour, int minute) {
 5                 // TODO Auto-generated method stub
 6                 AndroidAnalogClockActivity.this.hour=hour;
 7                 AndroidAnalogClockActivity.this.minute=minute;
 8                 showDate(year, month, day, hour, minute);
 9             }
10         });

4.显示方法

1     // 在EditText中显示
2     private void showDate(int year, int month, int day, int hour, int minute) {
3         EditText txtShow = (EditText) this.findViewById(R.id.txtShow);
4         txtShow.setText("选择的日期:" + year + "年" + (month+1) + "月" + day + "日" + hour
5                 + "时" + minute + "分");
6     }

注意:获得的月份是从0开始的,因此实际月份要+1

你可能感兴趣的:(Lock)