2015-10-13 46 views
0

我有一個活動2 EditText(startDate和endDate)。如何使用一個DatePickerDialog多個EditText

我創建了一個功能,我傳遞一個EditText,它會顯示一個datepicker:

private void showDatePicker(EditText et) { 

    Calendar calendar = Calendar.getInstance(); 

    DatePickerDialog picker = new DatePickerDialog(getActivity(), this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); 

    if (!Global.isEmpty(et)) { 

     try { 
      SimpleDateFormat sdf = new SimpleDateFormat(Global.USER_FRIENDLY_DATE_FORMAT, Locale.getDefault()); 
      calendar.setTime(sdf.parse(et.getText().toString())); 
     } catch (ParseException e) { 
      Toast.makeText(getActivity(), "Error setting the date", Toast.LENGTH_SHORT).show(); 
     } 
    } 
    picker.show(); 
} 

當我拿起一個日期,我會得到一個回調到onDateSet()函數的日期choosen 。

我的問題是,我怎麼知道它是哪個EditText?

我知道有一個「DatePicker視圖」作爲參數傳遞給onDateSet(),但似乎無法弄清楚如何使用它,或者即使我應該。

+0

看看這個[文章](http://stackoverflow.com/questions/30431250/how-to-achieve-multiple-datepicker-functionality-with-two-buttons-and-保存-那些/ 30433506#30433506)。 –

回答

1

你可以通過調用picker.getDatePicker()setTag()。同樣標籤的標籤設置爲您DatepickerDialog的DatePicker的對象可以從日期選擇對象的回調函數來檢索onDateSet()

DatePickerDialog picker = new DatePickerDialog(getActivity(), listner , calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); 
DatePicker pick = picker.getDatePicker().setTag(et.getId()); 

public void onDateSet(DatePicker datePicker, int i, int i1, int i2) { 
    Log.d("", " " + datePicker.getTag()); 
// based on the returned tag you can decide what to do... 

} 
+0

不,這個if語句應該在onDateSet()中,這是一個監聽器回調函數,我沒有參考EditText。除非我將「選擇的」EditText設置爲全局變量。但是,我想知道是否有可能使用onDateSet()中傳遞的DatePicker來實現此目的。 –

+0

嘗試在創建對話框時在DatePicker對象中設置標籤,並在回調中將其與其進行比較。 – Atmaram

+0

我也想到了這一點,但選擇器對象上沒有setTag方法:) –

0

您可以使用此代碼作爲我的應用程序

public void showDialog(EditText ed){ 
    final EditText e = ed; 
    e.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      final Calendar c = Calendar.getInstance(); 
      int mYear = c.get(Calendar.YEAR); // current year 
      int mMonth = c.get(Calendar.MONTH); // current month 
      int mDay = c.get(Calendar.DAY_OF_MONTH); // current day 

      dpd = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() { 
       @Override 
       public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) { 
        e.setText(dayOfMonth + "/"+ (monthOfYear+1) + "/" + year); 
       } 
      },mYear,mMonth,mDay); 
      dpd.show(); 
     } 
    }); 
} 
0
DatePickerDialog picker= new DatePickerDialog(getActivity(), this, year, month,day); 
picker.getDatePicker().setTag("id") 
相關問題