首先介绍一下TimePicker 的使用
xml文件代码部分
<TimePicker android:id="@+id/firsttime1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/firsttime1" android:text="获取Timepicker的值" />
2.MainActivity部分
private TimePicker firstTimePicker; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); firstTimePicker=(TimePicker)findViewById(R.id.firsttime1); firstTimePicker.setIs24HourView(true);//设置是否为24小时制 firstTimePicker.setCurrentHour(12);//设置显示的时间,默认的是显示当前的时间 firstTimePicker.setCurrentMinute(12); TimeList timel=new TimeList(); //firstTimePicker.setOnTimeChangedListener(timel); button=(Button)findViewById(R.id.button); ButtonLis bl=new ButtonLis(); button.setOnClickListener(bl);//通过下面的按钮来Toast时间 } class ButtonLis implements OnClickListener{ @Override public void onClick(View v) { int hour=firstTimePicker.getCurrentHour(); int min=firstTimePicker.getCurrentMinute(); Toast.makeText(getApplicationContext(), hour+":"+min, Toast.LENGTH_SHORT).show(); } } class TimeList implements OnTimeChangedListener{ //view 该对象代表的timepicker //hourofday :用户选择的小时 @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { Toast.makeText(getApplicationContext(), hourOfDay+"-"+minute, Toast.LENGTH_LONG).show(); } }
接下来介绍一下DatePicker的使用
xml文件的代码部分
<DatePicker android:id="@+id/datepick" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/but" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/datepick" android:text="获取datepicker的值" />
mainactivity部分
private DatePicker date; private Button but; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); date=(DatePicker)findViewById(R.id.datepick); but=(Button)findViewById(R.id.but); date.updateDate(2013, 6, 6);//设置一个显示时间,否则是当前系统时间 ButLis butlis=new ButLis(); but.setOnClickListener(butlis); } class ButLis implements OnClickListener{ @Override public void onClick(View v) { int year=date.getYear(); int mouth=date.getMonth(); int day=date.getDayOfMonth(); Toast.makeText(getApplicationContext(), "今天是"+year+"年"+mouth+"月"+day+"日", Toast.LENGTH_LONG).show(); } }
本文出自 “Java大白的战地” 博客,请务必保留此出处http://8023java.blog.51cto.com/10117207/1660199
Android中时间日期的使用TimePicker和DatePicker
原文地址:http://8023java.blog.51cto.com/10117207/1660199