2016-02-21 106 views
0

在我剛纔的問題Make button method if button clicked or not cliked,我發現我的回答是這樣的:停止一個Runnable

Handler visibilityToggler; 
Runnable visivilityRunnable; 


    visibilityToggler = new Handler(); 

     visivilityRunnable = new Runnable() { 
      @Override 
      public void run() { 

       // isUserClickedButton is used to keep record if user has pressed button within 1 sec 
       // keep isUserClickedButton = true for first time as it will run 
       if (!isUserClickedButton) { 

        // user not pressed button 
        Toast.makeText(context,"You are not pressed the Button",Toast.LENGHT_LONG).show(); 
       } 

       // toggle visibility 
       Random generator = new Random(); 
       number = generator.nextInt(16); 

       for (int i = 0; i < buttons.length; i++) { 
        if (i == number) 
         buttons[i].setVisibility(View.VISIBLE); 
        else 
         buttons[i].setVisibility(View.INVISIBLE); 
       } 

      // again start the visibility 
       visibilityToggler.postDelayed(visivilityRunnable,1000); 

       // make it false as visibility is toggled and we want to track button pressed from start 
       isUserClickedButton = false; 


      } 
     }; 

visibilityToggler.postDelayed(visivilityRunnable,1000); 

現在的問題是:如何阻止一個Runnable?
任何人都可以給一個代碼示例?

UPDATE:

我有一個按鈕

  public void onClick(View v){ 
      visibilityToggler.removeCallbacks(visivilityRunnable); 
      }   

但可運行不會停止使用removecallbacks(),任何人都可以幫忙嗎?

回答

1

我不知道,如果你想打破循環,但如果我理解你,我會建議你做一個靜態布爾變量,並停止它,只要你想

public static boolean isWorking=true; 
    for (int i = 0; i < buttons.length; i++) { 
       if(isWork){ 
       if (i == number) 
        buttons[i].setVisibility(View.VISIBLE); 
       else 
        buttons[i].setVisibility(View.INVISIBLE); 
      }else break;} 

現在,如果你想打破循環只是將isWork更改爲false

+0

哇!謝謝 – Ricci

+0

歡迎您好友 –

0

定義處理程序外部的可運行程序。然後撥打handler.removeCallbacks(visivilityRunnable);您想停止處理程序。