在switch语句中每个真实案例后暂停的处理程序

时间:2015-12-01 13:53:55

标签: java android

我有一个开关声明,如果为true,则会更改某些按钮的颜色。问题是如果点亮多个按钮,它们会同时点亮。我需要代码在每个真实的情况后暂停一秒钟。

public void PlaySequence() {

    //loops through arraylist and changes the background colour of the buttons that has the corresponding number assigned i.e. red = 0, blue = 1 etc.
    for (int i = 0; i < yourList.size(); i++) {
        switch (Integer.parseInt(yourList.get(i).toString())) {
            case 0:

                redButton.setBackgroundColor(Color.RED);
                revertButtonColour(0);
                break;
            case 1:
                blueButton.setBackgroundColor(Color.BLUE);
                revertButtonColour(1);
                break;

            case 2:
                greenButton.setBackgroundColor(Color.GREEN);
                revertButtonColour(2);
                break;
            case 3:
                yellowButton.setBackgroundColor(Color.YELLOW);
                revertButtonColour(3);
                break;
        }
    }

    Toast toast = Toast.makeText(this.getApplicationContext(), "Go!", Toast.LENGTH_SHORT);
    toast.show();
}

2 个答案:

答案 0 :(得分:0)

您应该将该代码放在一个单独的线程中,然后使用runOnUIThread()来更改按钮背景。

否则你将多次调用sleep,因此当UI线程处于休眠状态时,不会绘制对按钮的更改。

只需将代码放在runnable的run方法中,然后按以下方式启动它:

new Thread(new Runnable(){ //here your run() method }).start();

要使用runOnUIThread,您需要引用您的活动。

希望这有帮助。

答案 1 :(得分:0)

提取此方法:

void setColour(String colour) {
    switch (Integer.parseInt(colour)) {
        case 0:
            redButton.setBackgroundColor(Color.RED);
            revertButtonColour(0);
            break;
        case 1:
            blueButton.setBackgroundColor(Color.BLUE);
            revertButtonColour(1);
            break;
        case 2:
            greenButton.setBackgroundColor(Color.GREEN);
            revertButtonColour(2);
            break;
        case 3:
            yellowButton.setBackgroundColor(Color.YELLOW);
            revertButtonColour(3);
            break;
    }
}

然后使用postDelayed进行更新。

public void PlaySequence() {
    //copy the current list to a queue
    final Queue<String> queue = new ArrayDeque<String>(yourList);

    if (queue.isEmpty()) return; //no sequence to show

    final Handler handler = new Handler();

    final Runnable showNextColour = new Runnable() { 
         public void run() { 
              setColour(queue.pop()); //set colour to queue head

              if (!queue.isEmpty()) { //any more?
                  // schedule next one for one seconds time
                  handler.postDelayed(showNextColour, 1000);
              }
         } 
    };

    showNextColour.run(); //show first colour now
}