當我們發現在同一個Activity下需要寫兩個以上的datePickerDialog,可能會需要switch case來幫忙
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapv2withroutesetting);
alendar = Calendar.getInstance();
mYear = calendar.get(Calendar.YEAR);
mMonth = calendar.get(Calendar.MONTH);
mDay = calendar.get(Calendar.DAY_OF_MONTH);
dateText = (TextView)findViewById(R.id.dateText);
dateButton = (Button)findViewById(R.id.dateButton);
dateText2 = (TextView)findViewById(R.id.dateText2);
dateButton2 = (Button)findViewById(R.id.dateButton2);
dateButton.setOnClickListener(new OnClickListener(){
@SuppressWarnings("deprecation")
public void onClick(View view) {
//注意: 這裡要showDialog(0);
//也就是給他一個代號,讓switch case能夠使用
showDialog(0);
datePickerDialog.updateDate(mYear, mMonth, mDay);
}
});
dateButton2.setOnClickListener(new OnClickListener(){
@SuppressWarnings("deprecation")
public void onClick(View view) {
//注意: 這裡要showDialog(1);
//也就是給他一個代號,讓switch case能夠使用
showDialog(1);
datePickerDialog2.updateDate(mYear, mMonth, mDay);
}
});
}
//重點在這邊,可以用switch case來表示哪一個datePickerDialog是對應哪一個case的
//而這邊我datePickerDialog1對應的是1,而datePickerDialog2對應的是2
@Override
protected Dialog onCreateDialog(int id) {
switch(id){
//對應上方的showDialog(0);
case 0:
datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int month,
int day) {
mYear = year;
mMonth = month;
mDay = day;
dateText.setText("起始日期:"+setDateFormat(year,month,day));
dateFrom = setDateFormat(year,month,day);
}
}, mYear,mMonth, mDay);
return datePickerDialog;
//對應上方的showDialog(0);
case 1:
datePickerDialog2 = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int month,
int day) {
mYear = year;
mMonth = month;
mDay = day;
dateText2.setText("\t結束日期:"+setDateFormat(year,month,day));
dateTo = setDateFormat(year,month,day);
}
}, mYear,mMonth, mDay);
return datePickerDialog2;
}
//這邊要記得回傳null,或是你自訂的其他datePickerDialog
return null;
}
private String setDateFormat(int year,int monthOfYear,int dayOfMonth){
return String.valueOf(year) +"."
+ String.valueOf(monthOfYear + 1) +"."
+ String.valueOf(dayOfMonth);
}
你好,我用你的這個程式寫作方式,可以正常設定兩個datePickerDialog的時間,但是我發現會有一個問題
回覆刪除就是我設定好第一個datePickerDialog的日期,到我要設定第二個datePickerDialog時會出現跟第一個datePickerDialog
己設定好的日期一樣的日期,不知道您是否也有同樣問題呢??
Sure
刪除要改掉其實不難,
只要改成在每次開啟datePickerDialog的時候,
就預設成為目前日期就好😄