本代码实现的是一个获取当前时间和日期并能够选择时间日期的小实例 定义一个类,然后初始化定义 // 设置日期的参数 //获取当前日期的TextView private TextView now_date; //点击选择日期的按钮Button private Button change_date; private int now_year; private int now_month; private int now_day; private final static int DIALOG_DATE = 1; // 设置时间的参数 // 获取当前时间的TextView private TextView now_time; //点击选择时间的按钮Button private Button change_time; private int now_hours; private int now_minute; private int now_second; private final static int DIALOG_TIME = 0; 然后在onCreate方法里面实例化两个选项按钮和两个获取当前时间的TextView文本
//日期 now_date = (TextView) findViewById(R.id.now_date); change_date = (Button) findViewById(R.id.change_date); //时间 now_time = (TextView) findViewById(R.id.now_time); change_time = (Button) findViewById(R.id.change_time);
实例化后实现监听 // 日期的选择 change_date.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showDialog(0); } }); // 时间的选择 change_time.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showDialog(1); } });
在onCreate方法里面实现 // 获取当前时间值 Calendar c1 = Calendar.getInstance(); now_hours = c1.get(Calendar.HOUR_OF_DAY); now_minute = c1.get(Calendar.MINUTE); now_second = c1.get(Calendar.SECOND); updateDisplay2(); // 获取当前日期值 Calendar c = new GregorianCalendar(); now_year = c.get(Calendar.YEAR); now_month = c.get(Calendar.MONTH); now_day = c.get(Calendar.DAY_OF_MONTH); updateDisplay();
在OnCreate外面实现 private void updateDisplay() { StringBuilder buf = new StringBuilder(); buf.append(now_year).append("-").append(now_month + 1).append("-") .append(now_day).append(" "); now_date.setText(buf); // time_detial.setText(buf); time_detial.setText(now_date.getText().toString() + now_time.getText().toString()); } private void updateDisplay2() { StringBuilder buf = new StringBuilder(); buf.append(pad(now_hours)).append(":").append(pad(now_minute)) .append(":").append(pad(now_second)); now_time.setText(buf); // time_detial.setText(buf); }
通过Dialog显示出来 protected Dialog onCreateDialog(int id) { switch (id) { case 0: DatePickerDialog dpd = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { now_year = year; now_month = monthOfYear; now_day = dayOfMonth; updateDisplay(); } }, now_year, now_month, now_day); return dpd; case 1: TimePickerDialog tpd = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { now_hours = hourOfDay; now_minute = minute; updateDisplay2(); } }, now_hours, now_minute, true); return tpd; } return null; }