建立布局文件 activity_main.xml
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/date_dialog"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="显示日期" />
</RelativeLayout>
实现MainActivity.java文件
package com.example.datepickerdialog;
import java.util.Calendar;
import android.R.integer;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button date_dialog;
private static int DATE_PICKER=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
date_dialog=(Button)findViewById(R.id.date_dialog);
date_dialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DATE_PICKER);
}
});
}
@Override
@Deprecated
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
Calendar calendar=Calendar.getInstance();
Dialog dateDialog=new DatePickerDialog(MainActivity.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
Toast.makeText(MainActivity.this,year + "年" + (monthOfYear+1) + "月" + dayOfMonth + "日" , Toast.LENGTH_SHORT).show();
}
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));
return dateDialog;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
运行结果:
@author www.lelexie.com