packagecom.study.datetimepicker;importjava.text.SimpleDateFormat;importjava.util.Calendar;importandroid.os.Bundle;importandroid.app.Activity;importandroid.view.Menu;importandroid.widget.DatePicker;importandroid.widget.DatePicker.OnDateChangedListener;importandroid.widget.TextView;importandroid.widget.TimePicker;importandroid.widget.Toast;importandroid.widget.TimePicker.OnTimeChangedListener;public class MainActivity extends Activity implementsOnDateChangedListener,OnTimeChangedListener{privateTextView textView;privateDatePicker datePicker;privateTimePicker timePicker;
@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datePicker= (DatePicker)this.findViewById(R.id.datepicker);
timePicker= (TimePicker)this.findViewById(R.id.timepicker);
textView= (TextView)this.findViewById(R.id.textview);
datePicker.init(2001, 1, 25, this);//初始化日期
timePicker.setIs24HourView(true);//显示时间是否是按24小时制
timePicker.setOnTimeChangedListener(this);//注册事件
}
@Overridepublic booleanonCreateOptionsMenu(Menu menu) {//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);return true;
}//日期控件的触发
@Overridepublic void onDateChanged(DatePicker view, int year, intmonthOfYear,intdayOfMonth) {
Calendar calendar=Calendar.getInstance();
calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(),
timePicker.getCurrentHour(), timePicker.getCurrentMinute());
SimpleDateFormat format= new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
textView.setText(format.format(calendar.getTime()));
}//时间空间的触发
@Overridepublic void onTimeChanged(TimePicker view, int hourOfDay, intminute) {
Toast.makeText(MainActivity.this, "hourOfDay:" + hourOfDay + " minute:" + minute, 1).show();
}
}