本文主要介绍DatePicker日期选择器、TimePicker时间选择器的使用,具体操作看代码。
1.DatePickerActivity.java
//DatePicker日期选择器、TimePicker时间选择器 使用
public class DatePickerActivity extends Activity {
private Button datePickerButton;
private DatePicker datePicker1;
private TimePicker timePicker1;
//默认生成系统当前时间
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
String str=sdf.format(new Date());
int year=Integer.parseInt(str.substring(0, 4));
int month=Integer.parseInt(str.substring(5,7))-1;
int day=Integer.parseInt(str.substring(8,10));
int hour=Integer.parseInt(str.substring(11,13));
int minute=Integer.parseInt(str.substring(14,16));
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.date_picker);
setTitle("DatePicker、TimePicker示例!");
datePicker1=(DatePicker)findViewById(R.id.datePicker1);
timePicker1=(TimePicker)findViewById(R.id.timePicker1);
datePickerButton=(Button)findViewById(R.id.datePickerButton1);
datePicker1.init(year,month,day, null);
timePicker1.setCurrentHour(hour);
timePicker1.setCurrentMinute(minute);
timePicker1.setIs24HourView(true);
datePickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int Month=datePicker1.getMonth()+1;
setTitle("你选择的是:"+datePicker1.getYear()+"年"+Month+"月"+datePicker1.getDayOfMonth()+"日 "+timePicker1.getCurrentHour()+"小时"+timePicker1.getCurrentMinute()+"分");
}
});
}
}
2.布局文件date_picker.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TimePicker
android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/datePickerButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="获取日期" />
</LinearLayout>
3. 注意:需要在AndroidManifest.xml注册相应Activity.