一、简介
二、方法
最日常的使用方法了
日期控件DatePicker
时间控件TimePicker
月份从0开始
三、代码实例
效果图:
代码:
fry.Activity01
1 package fry; 2 3 import com.example.DatePicherDemo1.R; 4 5 import android.app.Activity; 6 import android.os.Bundle; 7 import android.widget.DatePicker; 8 import android.widget.DatePicker.OnDateChangedListener; 9 import android.widget.TimePicker; 10 import android.widget.TimePicker.OnTimeChangedListener; 11 import android.widget.Toast; 12 13 public class Activity01 extends Activity implements OnDateChangedListener,OnTimeChangedListener{ 14 private DatePicker datePicker1; 15 private TimePicker timePicker1; 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 // TODO Auto-generated method stub 19 super.onCreate(savedInstanceState); 20 setContentView(R.layout.activity01); 21 setTitle("时间日期控件测试"); 22 23 datePicker1=(DatePicker) findViewById(R.id.datePicker1); 24 timePicker1=(TimePicker) findViewById(R.id.timePicker1); 25 //初始化日期,并设置日期被改变后的监听事件 26 datePicker1.init(2017, 8, 7, this); 27 //设置时间以24小时制 28 timePicker1.setIs24HourView(true); 29 //设置时间被改变后的监听时间 30 timePicker1.setOnTimeChangedListener(this); 31 32 } 33 @Override 34 public void onDateChanged(DatePicker view, int year, int monthOfYear, 35 int dayOfMonth) { 36 // TODO Auto-generated method stub 37 Toast.makeText(this, "日期被改变为: "+year+"."+(monthOfYear+1)+"."+dayOfMonth, Toast.LENGTH_SHORT).show(); 38 39 } 40 @Override 41 public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { 42 // TODO Auto-generated method stub 43 Toast.makeText(this, "时间被改变为: "+hourOfDay+":"+minute, Toast.LENGTH_SHORT).show(); 44 } 45 }
/DatePicherDemo1/res/layout/activity01.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" > 6 7 <DatePicker 8 android:id="@+id/datePicker1" 9 android:layout_width="match_parent" 10 android:layout_height="wrap_content" 11 /> 12 13 <TimePicker 14 android:id="@+id/timePicker1" 15 android:layout_width="match_parent" 16 android:layout_height="wrap_content" 17 /> 18 19 </LinearLayout>
四、收获
1、初始化日期,并设置日期被改变后的监听事件
datePicker1.init(2017, 8, 7, this);
2、设置时间以24小时制
timePicker1.setIs24HourView(true);
3、设置时间被改变后的监听事件
timePicker1.setOnTimeChangedListener(this);