1. 程式人生 > >Android中關於DatePickerDialog與TimePickerDialog的結合使用

Android中關於DatePickerDialog與TimePickerDialog的結合使用

package org.crazyit.dialog;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
/**
 * @author 吳日輝
 */
public class DateDialog extends Activity {
//用來拼接日期和時間,最終用來顯示的
StringBuilder str = new StringBuilder("");
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button dateBn = (Button) findViewById(R.id.dateBn);
// 為“設定日期”按鈕繫結監聽器。
dateBn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View source) {
Calendar c = Calendar.getInstance();
// 直接建立一個DatePickerDialog對話方塊例項,並將它顯示出來
Dialog dateDialog = new DatePickerDialog(DateDialog.this,
// 繫結監聽器
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker dp, int year,
int month, int dayOfMonth) {
str.append(year + "-" + (month + 1) + "-"
+ dayOfMonth + " ");
Calendar time = Calendar.getInstance();
Dialog timeDialog = new TimePickerDialog(
DateDialog.this,
// 繫結監聽器
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(
TimePicker tp,
int hourOfDay, int minute) {
str.append(hourOfDay + ":"
+ minute);
EditText show = (EditText) findViewById(R.id.show);
show.setText(str);
}
}
// 設定初始時間
, time.get(Calendar.HOUR_OF_DAY), time
.get(Calendar.MINUTE)
// true表示採用24小時制
, true);
timeDialog.setTitle("請選擇日期");
timeDialog.show();


}
}
// 設定初始日期
, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c
.get(Calendar.DAY_OF_MONTH));
dateDialog.setTitle("請選擇日期");
dateDialog.show();
}
});
}
}