1. mian.xml
2. 12 小时
TimePicker timePicker=(TimePicker)findViewById(R.id.timePicker1); //获取对象 timePicker.setCurrentHour(8); //设置小时 timePicker.setCurrentMinute(12); //设置分钟
3. 24 小时
TimePicker timePicker=(TimePicker)findViewById(R.id.timePicker1); //获取对象 timePicker.setCurrentHour(15); //设置小时 timePicker.setCurrentMinute(12); //设置分钟 timePicker.setIs24HourView(true); //设置24小时制显示
4.显示时间
TimePicker timePicker=(TimePicker)findViewById(R.id.timePicker1); timePicker.setCurrentHour(15); timePicker.setCurrentMinute(12); timePicker.setIs24HourView(true); timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "当前时间为:"+hourOfDay+"点"+minute+"分", Toast.LENGTH_LONG).show(); //显示时间信息 } });
5.判断是否是24小时制 根据结果进行显示
main.xml
firstActivity
Button bt1=(Button)findViewById(R.id.button1); //获取按钮对象 final TimePicker timePicker=(TimePicker)findViewById(R.id.timePicker1); //获取TimePicker对象 timePicker.setCurrentHour(15); //设置小时 timePicker.setCurrentMinute(12); //设置分钟 bt1.setOnClickListener(new View.OnClickListener() { //设置按钮监听器 @Override public void onClick(View v) { // TODO Auto-generated method stub int hour,minite; boolean is24v; hour=timePicker.getCurrentHour(); //获取显示小时 minite=timePicker.getCurrentMinute(); //获取显示分钟 is24v=timePicker.is24HourView(); //获取是否为24小时制 if(is24v) //24小时制的情况 { Toast.makeText(getApplicationContext(), "当前时间为:"+hour+"小时"+minite+"分钟", Toast.LENGTH_LONG).show(); //显示时间信息 } else //上午/下午模式 { if (hour<12) { Toast.makeText(getApplicationContext(), "当前时间为:上午"+hour+"小时"+minite+"分钟", Toast.LENGTH_LONG).show(); //显示时间信息 } else { Toast.makeText(getApplicationContext(),"当前时间为:下午"+(hour-12)+"小时"+minite+"分钟", Toast.LENGTH_LONG).show(); //显示时间信息 } } } });