2016-10-02 50 views
1

我一直在試圖弄清楚如何使用'處理程序()'倒計時器,我仍然不知道如何使它的應用程序將執行「完成」行時倒計數達到0.我正在尋找退出處理程序,並返回到活動代碼時,它已完成其作業

我是無論代碼行是需要我輸入'UpdateGUI()'退出runnable並返回到顯示「完成」的主要活動。

我還沒有編碼很長,所以也許這是一個明顯的答案,但我不能找到它在這個頁面上的任何線程...

一些幫助,將不勝感激:-)

謝謝

public class MainActivity extends AppCompatActivity { 

    int i = 10; 
    TextView tv; 
    final Handler myHandler = new Handler(); 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     Button but = (Button) findViewById(R.id.button); 

     but.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       tv = (TextView) findViewById(R.id.textView); 

       Timer myTimer = new Timer(); 
       myTimer.schedule(new TimerTask() { 
        @Override 
        public void run() { 
         UpdateGUI(); 
        } 
       }, 0, 1000); 
       tv = (TextView) findViewById(R.id.textView); 
       tv.setText("Finished"); 
      } 
     }); 
    } 

    private void UpdateGUI() { 
     if (i == 0) { 
      //this is where i need to enter the code!! 
     } 
     else 
      i--; 
     myHandler.post(myRunnable); 
    } 

    final Runnable myRunnable = new Runnable() { 
     public void run() { 
      tv.setText(String.valueOf(i)); 
     } 
    }; 
} 

回答

0

如果我理解正確的情況下,你需要在運行時使用的處理方法postDelayed的一段時間後,您可運行(可運行,timeOutInMillis)

UPDATE:例如處理程序定時器的

int timesRun; 
Handler handler = new Handler(); 
Runnable runnable = new Runnable() { 
    public void run() { 
     runTimer(); 
     i++; 
    } 
}; 

// call it in button callback 
    public void runTimer(){ 
     // update your timer here 
     if (i != 10) // if 10 seconds not passed run it one more time 
     handler.postDelayed(runnable, 1000); // run every second 
    } 

注意,這不是最優雅的方式來做到這一點,不過,它應該工作

+0

謝謝您的答覆。這是否意味着runnable只能運行'x'秒,然後返回主要活動? –

+0

我喜歡runnable,當按鈕被按下時,runnable會給出10秒的倒計時,然後當runnable結束時,我希望文本說「完成」,然後應用程序的其餘部分將繼續從主要活動 –

+0

@DogBarrett我已添加示例 – temnoi

相關問題