一、DatePicker和DatePickerDialog的使用方法
DatePicker用于设置日期。所有的控件都是事先设置好的,不需要自己设置。
1.调用showDialog方法:
需要传递一个ID,当该ID与onCreateDialog方法中的ID一致就会执行创建方法。
showDialog(DATE_PICKER_ID);
2.重写onCreateDialog方法:
当Activity创建Dialog时就会调用该方法。即当调用showDialog方法时就会调用。同样月份是从0开始的。onDateSetListener为set按钮的监听器,后面的三个参数为默认显示的日期。
@Override
protected Dialog onCreateDialog(int id) {
switch(id){
case DATE_PICKER_ID:
return new DatePickerDialog(this,onDateSetListener,2011,9,30);
}
return null;
}
3.声明监听器,使用匿名内部类:
应该注意monthOfYear这个参数是从0开始的。为了显示方便而加1。
DatePickerDialog.OnDateSetListener onDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
System.out.println(year+"-"+(monthOfYear+1)+"-"+dayOfMonth);
}
};
完整代码:
package com.android.activity;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
public class DatePickerActivity extends Activity {
private Button showdp = null;
private static final int DATE_PICKER_ID = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showdp = (Button)findViewById(R.id.showdp);
showdp.setOnClickListener(new ShowDPListener());
}
class ShowDPListener implements OnClickListener{
public void onClick(View v) {
showDialog(DATE_PICKER_ID);
}
}
DatePickerDialog.OnDateSetListener onDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
System.out.println(year+"-"+(monthOfYear+1)+"-"+dayOfMonth);
}
};
@Override
protected Dialog onCreateDialog(int id) {
switch(id){
case DATE_PICKER_ID:
return new DatePickerDialog(this,
onDateSetListener,2011,9,30);
}
return null;
}
}
运行结果: