2014-11-05 74 views
0

我想在一個活動中從用戶處獲取多個日期。該活動實現onDateSetListener。使用DatePickerDialog選擇多個日期

我有4個按鈕,每個按鈕都會調用showDialog函數來顯示DatePickerDialog。在OnDateSet函數中,我如何區分4個按鈕? (如,我如何檢查哪個按鈕叫做這個對話框)。

我和TimePicker也有類似的問題,但我猜DatePicker的解決方案也適用於TimePicker。

+0

可能重複:[stackoverflow.com/questions/3734981/multiple-datepickers-in-same-activity](http://stackoverflow.com /問題/ 3734981 /多datepickers功能於同一活動) – Endor 2014-11-05 08:00:28

回答

1

您可以爲您的DatePicker添加標籤。當您創建對話框時,請執行以下操作:

mDatePickerDialog.getDatePicker().setTag(FIRST_DIALOG); 

其中FIRST_DIALOG例如是整數或字符串; 然後你只用一個onDateSetListener:

onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) 
{ 
    int code = (Integer) view.getTag(); //if you are using integers 
    switch(code) 
    { 
     // switch between your datePicker 
    } 

} 
0

與下面的代碼創建CustomDatePickerDialog

public class CustomDatePickerDialog extends DatePickerDialog 
{ 
    public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth,View attachedView) 
    { 
     super(context, callBack, year, monthOfYear, dayOfMonth); 
     getDatePicker().setTag(attachedView.getId()); 
    } 

    public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) 
    { 
     super(context, callBack, year, monthOfYear, dayOfMonth); 
    } 

    public CustomDatePickerDialog(Context context, int theme, OnDateSetListener listener, int year, int monthOfYear, int dayOfMonth) 
    { 
     super(context, theme, listener, year, monthOfYear, dayOfMonth); 
    } 
} 

這樣稱呼它下面

btnSelectDate.setOnClickListener(new View.OnClickListener() 
{ 
    @Override 
    public void onClick(View view) 
    { 
     CustomDatePickerDialog customDatePickerDialog = new CustomDatePickerDialog(MainActivity.class,dateSetListener,2014,10,1,view); 
     customDatePickerDialog.show(); 
    } 
}); 

你會得到哪個按鈕在聽者

調用對話框如下圖所示
DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() 
{ 
    @Override 
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) 
    { 
     int viewID = view.getTag(); 
     switch(viewID) 
     { 
      case R.id.btnDatePicker1; 
      { 
       //DO Something 
      } 
      case R.id.btnDatePicker2; 
      { 
       //DO Something 
      } 
     } 
    } 
}; 

注:在自定義對話框所需的getDatePicker API等級11()調用