首页 > 代码库 > Android --时间控件的使用
Android --时间控件的使用
1. mian.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/LL" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TimePicker android:id="@+id/timePicker1" android:layout_width="match_parent" android:layout_height="wrap_content" > </TimePicker></LinearLayout>
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
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/LL"> <TimePicker android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/timePicker1"> </TimePicker> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/button1" android:text="@string/btn1"> </Button></LinearLayout>
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(); //显示时间信息 } } } });
Android --时间控件的使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。