2014-03-26 52 views
0

我正在處理這個android應用程序,用戶在其中點擊選擇日期按鈕並彈出日期選擇器對話框,用戶可以設置日期並按設置按鈕對話框。我無法獲得設置按鈕後面的事件監聽器。我想讓用戶在該設置按鈕後面的對話框中設置日期。爲DatePicker對話框的「設置」按鈕創建事件監聽器

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_locations); 


     pickBtn = (Button) findViewById(R.id.pickDateButton); 
      final Calendar c = Calendar.getInstance(); 
      year = c.get(Calendar.YEAR); 
      month = c.get(Calendar.MONTH); 
      day = c.get(Calendar.DAY_OF_MONTH); 

      month = month + 1; 

     pickBtn.setOnClickListener(new View.OnClickListener() { 
      @SuppressWarnings("deprecation") 
      @Override 
      public void onClick(View v) { 
       showDialog(DATE_PICKER_ID); 

      } 
     }); 

    } 

    private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() { 

     // when dialog box is closed, below method will be called. 
     public void onDateSet(DatePicker view, int selectedYear, 
       int selectedMonth, int selectedDay) { 
      Toast.makeText(getApplicationContext(),"fdf", 
         Toast.LENGTH_LONG).show(); 
      Toast.makeText(getApplicationContext(), "Tracking Stopped", 
         Toast.LENGTH_LONG).show(); 
      year = selectedYear; 
      month = selectedMonth; 
      day = selectedDay; 

     } 
    }; 

我寫了正確的聽衆嗎?它不會在監聽器中顯示Toast消息,所以當用戶按下set按鈕並關閉對話框時,它不會進入它內部。

+0

編輯您的文章幷包含'showDialog'代碼或任何顯示DiatePickerDialog的位置。 – adneal

回答

0

對於大多數情況下你做的是正確的,但嘗試這樣做。

static final int DATE_PICKER_ID= 999; 

protected Dialog onCreateDialog(int id) { 

    switch (id) { 


      case DATE_PICKER_ID: 

     return new DatePickerDialog(this, datePickerListener , year, month, day); 
    } 
    return null; 
} 

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() { 
    // onDateSet method 
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { 


     //your code here 
    } 
}; 
1

是的,你的聽衆是正確的,但你沒有設置你的對話的監聽器。所以我建議你重寫方法onCreateDialog。像上面的代碼:

@Override 
protected Dialog onCreateDialog(int id) { 
    switch (id) { 
    case DATE_PICKER_ID: 

     // open datepicker dialog. 
     // set date picker for current date 
     // add pickerListener listner to date picker 
     return new DatePickerDialog(this, pickerListener, year, month,day); 
    } 
    return null; 
} 

這樣的活動是要聽您剛剛創建DatePickerDialog實例的變化。

由於showDialog(DATE_PICKER_ID)和onCreateDialog(int id)已被棄用。我建議你在不使用這些方法的情況下創建自己的DatePickerDialog實例。像

pickBtn.setOnClickListener(new View.OnClickListener() { 
     @SuppressWarnings("deprecation") 
     @Override 
     public void onClick(View v) { 
      new DatePickerDialog(this, pickerListener, year, month,day); 
     } 
    }); 
相關問題