时间选择器timepicker和日期选择器datepicker
DatePicker用init方法初始化日期并且使用setOnDateChangedListener。
TimePicker直接使用setOnTimeChangedListener来处理时间选择器。
而且都可以使用Dialog方法来显示选择器对话框,视觉效果很好。
public class MainActivity extends Activity {
private TimePicker timePicker;
private DatePicker datePicker;
private Calendar cal;
private int year, month, day, hour, minute;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
//获取日历对象
cal = Calendar.getInstance ();
//获取时分秒
year = cal.get (Calendar.YEAR);
month = cal.get (Calendar.MONTH) + 1;
day = cal.get (Calendar.DAY_OF_MONTH);
hour = cal.get (Calendar.HOUR_OF_DAY);
minute = cal.get (Calendar.MINUTE);
setTitle (year + "-" + month + '-' + day + "-" + hour + ":" + minute);
datePicker = (DatePicker) findViewById (R.id.datePicker);
timePicker = (TimePicker) findViewById (R.id.timePicker);
//如果是datepciker 就初始datepicker
datePicker.init (year, cal.get (Calendar.MONTH), day, new DatePicker.OnDateChangedListener () {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
setTitle (year + "-" + (monthOfYear + 1) + '-' + dayOfMonth);
}
});
//如果是timepicker就直接设置监听器
timePicker.setOnTimeChangedListener (new TimePicker.OnTimeChangedListener () {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
setTitle (hourOfDay+":"+minute);
}
});
//日期选择对话框,选择效果更加明显
new DatePickerDialog (this, new DatePickerDialog.OnDateSetListener () {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
setTitle (year + "-" + (monthOfYear + 1) + '-' + dayOfMonth);
}
},year, cal.get (Calendar.MONTH) ,day).show ();
//时间选择对话框,效果同上
new TimePickerDialog (this, new TimePickerDialog.OnTimeSetListener () {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
setTitle (hourOfDay+":"+minute);
}
},hour,minute,true).show ();
}
}