2013-03-01 56 views
6

TimePickerDialog.onTimeSetListener我用下面的代碼顯示<code>TimePickerDialog</code>不叫

TimePickerDialog dialog = new TimePickerDialog(this, new OnTimeSetListener() { 

     @Override 
     public void onTimeSet(TimePicker view, int hourOfDay, int minute) { 
      System.out.println("onTimeSet"); 
     } 
    }, 20, 15, true); 
    dialog.setTitle("Test"); 
    dialog.setButton(TimePickerDialog.BUTTON_POSITIVE, "Done", new OnClickListener() { 

     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      System.out.println("Done"); 
     } 
    }); 
    dialog.setButton(TimePickerDialog.BUTTON_NEGATIVE, "Cancel", new OnClickListener() { 

     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      System.out.println("Cancel"); 
     } 
    }); 
    dialog.show(); 

在運行Android 2.3.7的設備時,onTimeSet方法不會被調用(在onClick方法做) 。在運行4.2.2的設備上,onTimeSet確實會被調用。

這裏發生了什麼?

回答

15

TimePickerDialog在Android 4.1.1之後發生了變化,並且存在關於取消TimePickerDialog和DatePickerDialog的錯誤。請先閱讀here。默認情況下,您不需要設置正面和負面按鈕。 TimePickerDialog和DatePickerDialog爲你處理。因此,如果這個取消問題對您不重要,請刪除正面和負面按鈕的設置。如果你刪除了這兩個版本,如果用戶點擊OK按鈕,你的onTimeSet方法將被調用。

但我建議,直到該bug將被修復使用定製AlertDialog與TimePicker小部件;

final TimePicker timePicker = new TimePicker(this); 
    timePicker.setIs24HourView(true); 
    timePicker.setCurrentHour(20); 
    timePicker.setCurrentMinute(15); 

    new AlertDialog.Builder(this) 
      .setTitle("Test") 
      .setPositiveButton(android.R.string.ok, new OnClickListener() { 

       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        Log.d("Picker", timePicker.getCurrentHour() + ":" 
          + timePicker.getCurrentMinute()); 
       } 
      }) 
      .setNegativeButton(android.R.string.cancel, 
        new OnClickListener() { 

         @Override 
         public void onClick(DialogInterface dialog, 
           int which) { 
          Log.d("Picker", "Cancelled!"); 
         } 
        }).setView(timePicker).show(); 
相關問題