main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/datepick"
android:text="@string/datepick"/>
</LinearLayout>
mainActivity.java
package com.fzq.datepickerdialog;
import android.R.integer;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
public class MainActivity extends Activity {
private Button datePick;
private final int DATE_PICKER_ID=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datePick=(Button)findViewById(R.id.datepick);
datePick.setOnClickListener(new ButtonListener());
}
class ButtonListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//此方法用于显示DatePickerDialog
showDialog(DATE_PICKER_ID);
}
}
//监听器,用于监听用户点下DatePickerDialogDE set按钮时,所设置的时间
DatePickerDialog.OnDateSetListener onDateSetListener=new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
// TODO Auto-generated method stub
System.out.println("年份:"+year+" 月份:"+month +"天:"+dayOfMonth);
}
};
protected Dialog onCreateDialog(int id){
switch (id) {
case DATE_PICKER_ID:
return new DatePickerDialog(this, onDateSetListener, 2017, 7, 25);
}
return null;
}
}