Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android編程之TimePickerDialog設置確定鍵導致OnTimeSetListener不響應問題

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

編輯:關於Android編程

在調用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對

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved