2012-06-29 118 views
0

我有幾個按鈕,我想隨機出現,然後在幾秒鐘後消失。我還想讓它們在可見時更改爲可點擊的狀態。製作按鈕出現,然後在Android幾秒鐘後消失

這是我有:?

public void fight() throws InterruptedException 
{ 
    Random g = new Random(); 
    int move; 
    for(int i = 0; i <= 3; i++) 
    { 
     move = g.nextInt(8); 
     buttons[move].setVisibility(View.VISIBLE); 
     buttons[move].setClickable(true); 

     try{ Thread.sleep(5000); }catch(InterruptedException e){ } 

     buttons[move].setVisibility(View.GONE); 
     buttons[move].setClickable(false); 
    } 

} 

當我嘗試,雖然,整個事情只是通過循環凍結20秒(大概每5秒的時間,並沒有發生任何想法

感謝。

+1

由於您正在睡覺UI線程,所以它處於凍結狀態。在後臺線程中運行計時器,並在回調中隱藏該按鈕。查看內置的Timer類(http://developer.android.com/reference/java/util/Timer.html) – xbonez

+0

是的。我肯定會使用帶有任務的Timer或帶有'Runnables'的'Handler'來實現它。 – davidcesarino

+0

我試過使用Timer,但是我得到了這個錯誤信息:CalledFromWrongThreadException:只有創建視圖層次結構的原始線程可以觸及其視圖。 – SpyMachine

回答

0

試試這個

public void fight() throws InterruptedException 
{ 
    Random g = new Random(); 
    int move; 
    runOnUiThread(new Runnable() 
    { 
     public void run() { 
      while(makeACondition) { 
      move = g.nextInt(8); 
      buttons[move].setVisibility(View.VISIBLE); 
      buttons[move].setClickable(true); 

      if (System.currentTimeMillis() % 5000 == 0) { 

       buttons[move].setVisibility(View.GONE); 
       buttons[move].setClickable(false); 
      } 
      } 
     } 
    } 

} 
+0

這只是讓他們都立即出現。另外,它就是'System.currentTimeMillis()',就像編輯一樣。 – SpyMachine

+0

更新後,試試這個 –

+0

仍然做同樣的事情 – SpyMachine

0
private Handler mMessageHandler = new Handler(); 
Random g = new Random(); 
int move; 

private Runnable mUpdaterRunnable = new Runnable() { 
    public void run() { 
     // hide current button 
     buttons[move].setVisibility(View.INVISIBLE); 
     // set next button 
     move = g.nextInt(8); 
     // show next button 
     buttons[move].setVisibility(View.VISIBLE); 

     // repeat after 5 seconds 
     mMessageHandler.postDelayed(mUpdaterRunnable, 5000); 
    } 
}; 

要開始,請使用move = g.nextInt(8);(避免爲空)和mMessageHandler.post(mUpdaterRunnable);

停止,mMessageHandler.removeCallbacks(mUpdaterRunnable);。正如xbonez所說,你也可以使用TimerTimerTask來實現這一點。

+0

在'mMessageHandler.postDelayed(mUpdaterRunnable,5000);''mUpdaterRunnable'給我一個'局部變量mUpdaterRunnable可能沒有被初始化'錯誤。任何想法? – SpyMachine

+0

不可能。如果您在類定義中全局定義了'mUpdaterRunnable',則它將被初始化。你在你身邊做錯了事。 – davidcesarino

0

你有沒有試過這種方法?

private int move; 
public void fight() throws InterruptedException 
{ 
    final Random g = new Random(); 
    runOnUiThread(new Runnable() 
    { 
     public void run() { 
      while(makeACondition) { 
      move = g.nextInt(8); 

      toggleButtonState(buttons[move]); 
      } 
     } 
    }); 
} 

private void toggleButtonState(final Button button) 
{ 
    new Handler().postDelayed(new Runnable() { 

     @Override 
     public void run() { 
      if(button.isEnabled()) 
       button.setVisibility(View.GONE); 
      else 
       button.setVisibility(View.VISIBLE); 

     } 
    }, 5000); 

} 
+0

你能測試嗎? – sunil