天天看点

DatePickerDialog使用方法

通过学习DatePickerDialog,它为弹出一个修改系统时间的模态对话框,创建DatePickerDialog步骤如下:

package com.dateandtime;

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 MainActivity extends Activity {

private Button showDatePickerButton = null;

//该常量用于标识DatePickerDialog

private static final int DATE_PICKER_ID = 1;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

showDatePickerButton = (Button) findViewById(R.id.showDatePickerButton);

showDatePickerButton.setOnClickListener(new ButtonListener());

}

private class ButtonListener implements OnClickListener {

@Override

public void onClick(View v) {

//此方法用于显示DatePickerDialog

showDialog(DATE_PICKER_ID);

}

}

//监听器,用户监听用户点下DatePikerDialog的set按钮时,所设置的年月日

DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {

//监听器,用户监听用户点下DatePikerDialog的set按钮时,所设置的年月日

@Override

public void onDateSet(DatePicker view, int year, int monthOfYear,

int dayOfMonth) {

System.out.println(year + "-" + monthOfYear + "-" + dayOfMonth);

}

};

//创建一个DatePickerDialog对象

@Override

protected Dialog onCreateDialog(int id) {

switch (id) {

case DATE_PICKER_ID:

//设置DatePickerDialog显示默认的时间

return new DatePickerDialog(this, onDateSetListener, 2010, 11, 25);

}

return null;

}

}