2014-07-06 100 views
0

我是Android開發新手,我正在嘗試製作遊戲。我有一個3x3的圖像按鈕和播放按鈕。當用戶點擊播放按鈕時,多個按鈕應點亮然後關閉。這工作正常。現在我試圖讓按鈕點亮並逐個關閉。所以如果comp_blocks包含[1,3,2]按鈕1會點亮,然後關閉,然後按鈕3會點亮....等等。這樣做的最佳方式是什麼?我希望按鈕保持點亮半秒鐘。如何在循環中暫停

編輯:爲了清楚起見,我希望每個人都點亮按鈕,然後按一下按鈕。按下按鈕,顯示1,關閉1,顯示3,關閉3.下次用戶按下按鈕時,將顯示新的序列。

 //Create pattern in comp_blocks 
     for(int i = 0; i < move_num+2; i++){ 
      comp_blocks.add(rand.nextInt(9) + 1); 
     } 

     //Display pattern 
     ListIterator<Integer> itr = comp_blocks.listIterator(); 
     while (itr.hasNext()) { 
      final Integer button_show = itr.next(); 
      switch (button_show){ 
       case 1: 
        button1.setBackgroundColor(getResources().getColor(R.color.garnet)); 
        break; 
       case 2: 
        button2.setBackgroundColor(getResources().getColor(R.color.garnet)); 
        break; 
       case 3: 
        button3.setBackgroundColor(getResources().getColor(R.color.garnet)); 
        break; 
       case 4: 
        button4.setBackgroundColor(getResources().getColor(R.color.garnet)); 
        break; 
       case 5: 
        button5.setBackgroundColor(getResources().getColor(R.color.garnet)); 
        break; 
       case 6: 
        button6.setBackgroundColor(getResources().getColor(R.color.garnet)); 
        break; 
       case 7: 
        button7.setBackgroundColor(getResources().getColor(R.color.garnet)); 
        break; 
       case 8: 
        button8.setBackgroundColor(getResources().getColor(R.color.garnet)); 
        break; 
       case 9: 
        button9.setBackgroundColor(getResources().getColor(R.color.garnet)); 
        break; 
      } 

回答

1

你可以使用一個可運行這樣

final Handler handler = new Handler(); 
handler.postDelayed(new Runnable() { 
    @Override 
    public void run() { 
    //Do something after 100ms 
    } 
}, 100); 

(從How to call a method after a delay in Android取代碼)

另一解決方案是創建與含有時的可變延伸buttonview一個類按鈕是最後一次按下,並創建聯合國更新方法,檢查時間限制elpased。 然後遍歷調用更新方法的按鈕。 第二個選項對我來說似乎更安全,因爲每次單擊該按鈕時都不會創建新任務。

編輯:

從我瞭解你對這個遊戲主循環,增加這樣的事情在裏面:

Time now=new Time; 
Time lastupdate=new Time; 
while(yourcondition)/*this is your main loop*/ 
{ 
    /*your stuff*/ 

     now.setToNow(); 
     if(now.toMillis(false)>lastupdate.toMillis(false)+TimeToWaitInMilliSeconds) 
     { 
      if(!buttonstolit.isEmpty()) { 
       resetTheButtons(); 
       lightThisButton(buttonstolit.get(0)); 
       buttonstolit.remove(0); 
       lastupdate.setToNow(); 
      } 
     } 

} 

凡buttonstolit被聲明爲列表。

使用buttonstolit.add(TheButtonToLitNext);將按鈕添加到等待列表中。您還需要在新序列前清除列表(或檢查它是否爲空,並等待另一個按鈕被按下)

我假設您在這裏使用整數來選擇按鈕(這似乎是這種情況從你的代碼)

+0

我試過這個,但它似乎並沒有工作。我會在運行功能中放入什麼?爲了清楚起見,我希望每按一次按鈕,每個人都點亮並熄滅。按下按鈕,顯示1,關閉1,顯示3,關閉3.下次用戶按下按鈕時,將顯示新的序列。 – easyxtarget

+0

爲什麼不使用包含序列的列表,並且有一個對象檢查時間並從列表中選取第一個元素並更新屏幕? – Lectem

+0

這將如何工作。我對android很新穎。 – easyxtarget