android中DatePicker和TimePicker的使用方法详解

本文以实例讲述了android中DatePicker和TimePicker的使用方法,具体步骤如下:
下面是实现具体功能的代码,其中main.xml代码为:




  

  

  

  


java代码为:

public class AndroidDemo5Activity extends Activity {

 // 记录当前的时间
 private int year;
 private int month;
 private int day;
 private int hour;
 private int minute;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 // TODO Auto-generated method stub
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 DatePicker date = (DatePicker) findViewById(R.id.datePicker);
 TimePicker time = (TimePicker) findViewById(R.id.timePicker);
 // 或许当前的年月日,小时,分钟
 Calendar ca = Calendar.getInstance();
 year = ca.get(Calendar.YEAR);
 month = ca.get(Calendar.MONTH);
 day = ca.get(Calendar.DAY_OF_MONTH);
 hour = ca.get(Calendar.HOUR);
 minute = ca.get(Calendar.MINUTE);

 // 初始化DatePicker
 date.init(year, month, day, new OnDateChangedListener() {

  @Override
  public void onDateChanged(DatePicker arg0, int year, int month,
   int day) {
  AndroidDemo5Activity.this.year = year;
  AndroidDemo5Activity.this.month = month;
  AndroidDemo5Activity.this.day = day;
  // 显示当前时间和日期
  showDate(year, month, day, hour, minute);
  }

 });

 // 为TimerPicker指定事件监听器
 time.setOnTimeChangedListener(new OnTimeChangedListener() {

  @Override
  public void onTimeChanged(TimePicker arg0, int hour, int minute) {
  AndroidDemo5Activity.this.hour = hour;
  AndroidDemo5Activity.this.minute = minute;
  }
 });
 }

 protected void showDate(int year2, int month2, int day2, int hour2,
  int minute2) {
 EditText text = (EditText) findViewById(R.id.show);
 text.setText("您的购买时间为:" + year2 + "年" + month2 + "月" + day2 + "日"
  + hour2 + "时" + minute2 + "分");

 }
}

运行效果如下图所示:

android中DatePicker和TimePicker的使用方法详解_第1张图片

你可能感兴趣的:(android中DatePicker和TimePicker的使用方法详解)