2014-04-29 63 views
0

我想設置一個表格的背景,以每隔500毫秒的紅色+白色開始閃爍,以便啓動。ideea是我希望它在此實現循環內的程序,我不知道如何。android如何更改表格的背景紅色白色延遲

if(Integer.parseInt(feedback.getText().toString()) == 0) 
       { 
         showup.setText("0"); 
         btnbool.setBackgroundColor(Color.RED); 
         btnbool.setText("FALSE"); 

       } 

我搜索過前面的主題,但我無法找到我的代碼工作的事,我不知道如何使用一個處理程序,使這個happen.There不會,如果我有問題調用一個函數來做到這一點。

+0

'timer'或'ScheduledExecutorService'(p.s然後使用'runOnUIThread'或'.post'來使用主線程) –

回答

0

在你的Activity類的頂部實現這些:

// isRed flag to set bg to red or white 
    boolean isRed = true; 
    Handler handler = new Handler(); 
    MyThread thread = new MyThread(); 

    private class MyThread implements Runnable { 
     public void run() { 
      showup.setText("0"); 
      if (isRed){ 
       btnbool.setBackgroundColor(Color.WHITE); 
       isRed=false; 
      } 
      else{ 
       btnbool.setBackgroundColor(Color.RED); 
       isRed=true; 
      } 

      btnbool.setText("FALSE"); 
      // will run every 500 milliseconds or whatever you wish 
      handler.postDelayed(thread, 500); 
     } 
    } 

在你的onCreate()運行的線程:

handler.post(thread); 

啓動/停止線程巴頓的onClick:

上您的活動頂部:

boolean threadStart = true; 

您的onclick事件中:

  if (threadStart){ 
       handler.removeCallbacks(thread); 
       threadStart=false; 
      } 

      else{ 
       handler.post(thread); 
       threadStart=true; 
      } 
+0

謝謝,它的工作,接受1分鐘的答案。 –

+0

另外我已經實現了一個按鈕來調整某些值,我應該怎麼做才能停止閃爍? –

+0

添加到我的答案。很高興它幫助你 –

0

TimerScheduledExecutorService

ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); 
當你想要啓動它

executorService.schedule(blinkRunnable, 500, TimeUnit.MILLISECONDS); 

可運行執行

private Runnable blinkRunnable = new Runnable(){ 
    @Override 
    public void run() { 
    if(Integer.parseInt(feedback.getText().toString()) == 0) 
    { 
     showup.post(new Runnable() { 
      @Override 
      public void run() { 
      showup.setText("0"); 
      btnbool.setBackgroundColor(Color.RED); 
      btnbool.setText("FALSE"); 
      } 
     }); 
    } 
    executorService.schedule(blinkRunnable, 500, TimeUnit.MILLISECONDS); // start again 
    } 
} 

PS你可以把顏色數組,使用索引,使事情更加靈活。