public class MainActivity extends AppCompatActivity { private TimePicker timePicker; private DatePicker datePicker; private Calendar cal; private int year; private int month; private int day; private int hour; private int minute; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //注册 对象 timePicker = (TimePicker)findViewById(R.id.timePicker); datePicker = (DatePicker)findViewById(R.id.datePicker); //获取年月日分秒信息 cal = Calendar.getInstance(); year = cal.get(Calendar.YEAR); month = cal.get(Calendar.MONTH); day = cal.get(Calendar.DAY_OF_MONTH) + 1 ; //月份从0开始的 所以要加1 hour = cal.get(Calendar.HOUR_OF_DAY); minute = cal.get(Calendar.MINUTE); //标题显示 setTitle(year + "-" + month +"-"+ day + "-" + hour + ":" + minute ); //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); } });
同时监听日期 时间 可以做闹钟
public class MainActivity extends AppCompatActivity { private TimePicker timePicker; private DatePicker datePicker; private Calendar cal; private int Year; private int month; private int day; private int hour; private int Minute; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //注册 对象 timePicker = (TimePicker)findViewById(R.id.timePicker); datePicker = (DatePicker)findViewById(R.id.datePicker); //获取年月日分秒信息 cal = Calendar.getInstance(); Year = cal.get(Calendar.YEAR); month = cal.get(Calendar.MONTH) + 1 ; //月份从0开始的 所以要加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.init(Year, cal.get(Calendar.MONTH), day, new DatePicker.OnDateChangedListener() { @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { month = monthOfYear + 1; day = dayOfMonth; Year = year; setTitle(Year + "-" + month +"-"+ day + "-" + hour + ":" + Minute ); } }); timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { hour = hourOfDay; Minute = minute; setTitle(Year + "-" + month +"-"+ day + "-" + hour + ":" + Minute ); } }); }
时间: 2024-11-04 17:10:27