控件DatePicker和TimePicker
对话框DatePickerDialog和TimePickerDialog
给出demo:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_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"/>
</LinearLayout>
MainActivity.java
package com.example.day101802;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
public class MainActivity extends Activity {
private DatePicker datePicker;
private TimePicker timePicker;
private Calendar cal;
private int year;
private int month;
private int day;
private int hour;
private int minute;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datePicker = (DatePicker) findViewById(R.id.datePicker1);
timePicker = (TimePicker) findViewById(R.id.timePicker1);
cal = Calendar.getInstance();
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH)+1;//month从0开始
day = cal.get(Calendar.DAY_OF_MONTH);
hour = cal.get(Calendar.HOUR);
minute = cal.get(Calendar.MINUTE);
//默认标题时间
setTitle(year+"-"+month+"-"+day+" "+hour+":"+minute);
// datePicker.init(year, cal.get(Calendar.MONTH), day, new OnDateChangedListener() {
//
// @Override
// public void onDateChanged(DatePicker datePicker, int year, int month, int day) {
//
// //改变后,里面变量为形参
// setTitle(year+"-"+(month+1)+"-"+day+" "+hour+":"+minute);
//
// }
// });
//对话框方式
new DatePickerDialog(this, new OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
// TODO Auto-generated method stub
setTitle(year+"-"+(month+1)+"-"+day+" "+hour+":"+minute);
}
}, year, cal.get(Calendar.MONTH), day).show();
// timePicker.setOnTimeChangedListener(new OnTimeChangedListener() {
//
// @Override
// public void onTimeChanged(TimePicker timePicker, int hour, int minute) {
//
// //改变后,里面变量为形参
// setTitle(year+"-"+(month+1)+"-"+day+" "+hour+":"+minute);
//
// }
// });
new TimePickerDialog(this, new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
// TODO Auto-generated method stub
setTitle(year+"-"+(month+1)+"-"+day+" "+hour+":"+minute);
}
}, hour, minute,true).show();
}
}
控件演示效果:
对话框演示效果: