一、源代码
package com.wyt.Android_DatePicker;
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 showID = null;
private static final int DATE_ID = 1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showID = (Button) findViewById(R.id.showID);
showID.setOnClickListener(new ShowButtonListener());
}
class ShowButtonListener implements OnClickListener{public void onClick(View v) {
// TODO Auto-generated method stub
//用于显示日期对话框,他会调用onCreateDialog()
showDialog(DATE_ID);
}
}
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
switch (id) {
case DATE_ID:
return new DatePickerDialog(this,onDateSetListener,2011,7,20);
}
return null;
}
//设置时间之后点击SET就会将时间改为你刚刚设置的时间
DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
System.out.println(year+"-"+monthOfYear+"-"+dayOfMonth);
}
};
}注意:这个不需要在xml文件中设置一个标签来制定这个显示日期的样式,DatePickerDialog是Android设置好的样式,直接用就OK了,但是也可以自己去改变一个更好看的样式
二、效果