标签:
DatePicker继承自FrameLayout类,日期选择控件的主要功能是向用户提供包含年、月、日的日期数据并允许用户对其修改。如果要捕获用户修改日期选择控件中的数据事件,需要为DatePicker添加OnDateChangedListener监听器。
示例:
一、全局模式
1、布局文件
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/id_datePicker1" 9 android:layout_width="wrap_content" 10 android:layout_height="wrap_content" /> 11 12 </LinearLayout>
2、activity
1 package base_ui; 2 3 import java.util.Calendar; 4 5 import com.example.allcode.R; 6 7 import android.app.Activity; 8 import android.app.DatePickerDialog; 9 import android.app.DatePickerDialog.OnDateSetListener; 10 import android.os.Bundle; 11 import android.widget.DatePicker; 12 import android.widget.DatePicker.OnDateChangedListener; 13 14 public class Ui_DatePicker extends Activity{ 15 private DatePicker datapicker; 16 private Calendar cal;//显示当前日期 17 private int year; 18 private int month; 19 private int day; 20 private int hour; 21 private int minute; 22 23 24 25 @Override 26 protected void onCreate(Bundle savedInstanceState) { 27 // TODO Auto-generated method stub 28 super.onCreate(savedInstanceState); 29 setContentView(R.layout.ui_datepickerdialog); 30 datapicker = (DatePicker) findViewById(R.id.id_datePicker1); 31 //获取日历的对象 32 cal=Calendar.getInstance(); 33 //获取年月日时分秒信息 34 year = cal.get(Calendar.YEAR); 35 month = cal.get(Calendar.MONTH)+1;//注意点 ,要加一 36 day = cal.get(Calendar.DAY_OF_MONTH); 37 hour = cal.get(Calendar.HOUR_OF_DAY); 38 minute = cal.get(Calendar.MINUTE); 39 40 setTitle("选择时间:"+year+"年-"+month+"月-"+day+"日 "+hour+"时-"+minute+"分"); 41 42 //datepicker 43 datapicker.init(year, cal.get(Calendar.MONTH), day, new OnDateChangedListener() { 44 45 @Override 46 public void onDateChanged(DatePicker view, int year, int month, int day) { 47 // TODO Auto-generated method stub 48 month++;//注意点。要加一 49 setTitle("当前时间:"+year+"年-"+month+"月-"+day+"日 "+hour+"时-"+minute+"分"); 50 } 51 }); 52 } 53 }
效果图:
二、对话框模式
对应上述示例42--51行代码
1 new DatePickerDialog(this, new OnDateSetListener() { 2 3 @Override 4 public void onDateSet(DatePicker view, int year, int month, int day) { 5 // TODO Auto-generated method stub 6 setTitle("当前时间:"+year+"年-"+month+"月-"+day+"日 "+hour+"时-"+minute+"分"); 7 } 8 }, year, cal.get(Calendar.MONTH), day).show(); //后三个参数相当于初始化
效果图:
标签:
原文地址:http://www.cnblogs.com/xqxacm/p/4567809.html