activity_main.xml:
<Button android:id="@+id/showDatePickerButton" android:text="@string/calendar" android:layout_width="wrap_content" android:layout_height="wrap_content" />
MainActivity.java:
package leihu.date_and_time; import android.os.Bundle; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.DatePicker; public class MainActivity extends Activity { private Button showDatePickerButton = null; //该常量用于标识DatePickerDialog private static final int DATE_PICKER_ID = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); showDatePickerButton = (Button)findViewById (R.id.showDatePickerButton); showDatePickerButton.setOnClickListener(new ButtonListener()); } private class ButtonListener implements OnClickListener{ @Override public void onClick(View v) { // TODO Auto-generated method stub //此方法用于显示DatePickerDialog showDialog(DATE_PICKER_ID); } } DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // TODO Auto-generated method stub System.out.println(year+"-"+monthOfYear+"—"+dayOfMonth); } }; protected Dialog onCreateDialog(int id){ switch(id){ case DATE_PICKER_ID: return new DatePickerDialog (this,onDateSetListener,2012,11,21); } return null; } }