Android編程之TimePickerDialog設置確定鍵導致OnTimeSetListener不響應問題

在調用TimePickerDialog時,如果要修改TimePickerDialog中確定鍵的名字,就需要調用setButton(int whichButton,CharSequence text,OnClickListener listener)方法,重新設置確定鍵的名字。但這樣直接設置,例如下面的代碼,就會造成OnTimeSetListener中onTimeSet不響應。

[java] 
TimePickerDialog timePickerDialog = new TimePickerDialog(this, 
                    new OnTimeSetListener() { 
                        @Override 
                        public void onTimeSet(TimePicker view, int hourOfDay, 
                                int minute) { 
                            System.out.println("time:" + hourOfDay + ":" 
                                    + minute); 
                        } 
                    }, calendar.get(Calendar.HOUR_OF_DAY), 
                    calendar.get(Calendar.MINUTE), false); 
 
            timePickerDialog.setTitle(R.string.title); 
            timePickerDialog.setButton(TimePickerDialog.BUTTON_POSITIVE, 
                    getString(R.string.ok), 
                    new DialogInterface.OnClickListener() { 
                        public void onClick(DialogInterface dialog, int which) { 
 
                        } 
                    }); 
            timePickerDialog.show(); 

所以,這裡要改一下setButton(int whichButton, CharSequence text,OnClickListener listener)中,最後傳入的參數,由OnClickListener listener改為TimePickerDialog對象本事,這樣就可以響應OnTimeSetListener中onTimeSet的方法。代碼如下:

[java]
TimePickerDialog timePickerDialog = new TimePickerDialog(this, 
        new OnTimeSetListener() { 
            @Override 
            public void onTimeSet(TimePicker view, int hourOfDay, 
                    int minute) { 
                System.out.println("time:" + hourOfDay + ":" 
                        + minute); 
            } 
        }, calendar.get(Calendar.HOUR_OF_DAY), 
        calendar.get(Calendar.MINUTE), false); 
 
timePickerDialog.setTitle(R.string.title); 
timePickerDialog.setButton(TimePickerDialog.BUTTON_POSITIVE, 
        getString(R.string.ok), timePickerDialog); 
timePickerDialog.show(); 

註意:setButton最後一個參數,不是OnClickListener對

You May Also Like