android-时间选择器和日期选择器

笛里谁知壮士心,沙头空照征人骨。这篇文章主要讲述android-时间选择器和日期选择器相关的知识,希望能为你提供帮助。
一、实现动态输入日期和时间
* DataPicker(日历选择器)
*DataPicker对象以init()方法指定DatePicker初始的年月日及OnDateChangedListener事件
* Timepicker(时间选择器)
*Timepicker对象直接以setOnTimeChangedListener()事件处理时间改变时称需要做的操作
*
* 二、动态输入日期和时间的对话框
* DataPickerDialog
*
* TimePickerDialog
*
* 三、监听器
* OnDateChangedListener
*当用户更改了DataPicker中的年、月、日将触发OnDateChangedListener监听器的onDateChange()事件
*
* OntimeChangedListener
*当用户更改了TimePicker中的时、分、秒将触发OnTimeChangedListener监听器的onTimeChange()事件
*
* OnDateSetListener
*当用户更改了DataPickerDialog中的年、月、日将触发OnDateSetListener监听器的onDateSet()事件
*
* OnTimeSetListener
*当用户更改了TimePickerDialog中的时、分、秒将触发OnTimeSetListener监听器的onTimeSet()事件
 
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 TimePicker timePicker;
private DatePicker datePicker;
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);

//获取日历的一个对象
cal=Calendar.getInstance();
//获取年月日时分秒信息
year=cal.get(Calendar.YEAR);
month=cal.get(Calendar.MARCH)+1;
day=cal.get(Calendar.DAY_OF_MONTH);
hour=cal.get(Calendar.HOUR_OF_DAY);
minute=cal.get(Calendar.MINUTE);
setTitle(year+"-"+month+"-"+day+"-"+hour+"-"+minute);

datePicker=(DatePicker) findViewById(R.id.datePicker);
timePicker=(TimePicker) findViewById(R.id.timePicker);

//datePicker初始化
datePicker.init(year, cal.get(Calendar.MARCH), day, new OnDateChangedListener() {

@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
setTitle(year+"-"+(monthOfYear+1)+"-"+dayOfMonth);
}
});

timePicker.setOnTimeChangedListener(new OnTimeChangedListener(){
【android-时间选择器和日期选择器】@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
setTitle(hourOfDay+":"+minute);
}});


new DatePickerDialog(this, new OnDateSetListener() {

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
setTitle(year+"-"+month+"-"+(monthOfYear)+"-"+dayOfMonth);
}
}, year, cal.get(Calendar.MARCH), day).show();


new TimePickerDialog(this, new OnTimeSetListener() {

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
setTitle(hourOfDay+":"+minute);
}
}, hour, minute, true).show();
}
}

    推荐阅读