在Android中实现流量信号

时间:2013-07-21 07:41:22

标签: android countdowntimer

我正在尝试实施一种交通信号,它会将颜色从红色变为绿色再变为黄色。为此,我使用了一个按钮,我将按钮的背景更改为受尊重的颜色。我正在使用CountDownTimer来实现此目的。这是我的代码:

public class MainActivity extends Activity {

    Button button1 = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button1 = (Button) findViewById(R.id.button1);
        button1.setBackgroundColor(Color.RED);
        while(true){
            change(Color.GREEN);
            change(Color.BLUE);
            change(Color.RED);
        }
    }

    void change(final int color) 
    {
        CountDownTimer ctd = new CountDownTimer(3000, 3000) 
        {

            @Override
            public void onTick(long arg0) {}

            @Override
            public void onFinish() {
                button1.setBackgroundColor(color);
            }
        };
        ctd.start();
    }
}

但是上面的代码似乎不起作用,按钮的颜色根本没有变化。这段代码有什么问题?

1 个答案:

答案 0 :(得分:1)

这对我有用:

public class TestActivity extends Activity {

    Button button1 = null;
    long timeout = Long.MAX_VALUE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button1 = (Button) findViewById(R.id.button1);
        button1.setBackgroundColor(Color.RED);

        change();
    }

    void change() {
        final int[] colors = {Color.GREEN, Color.BLUE, Color.RED};
        CountDownTimer ctd = new CountDownTimer(timeout, 3000) {

            int current = 0;

            @Override
            public void onTick(long arg0) {
                Log.d("TEST", "Current color index: " + current);
                button1.setBackgroundColor(colors[current++]);
                if (current == 3)
                    current = 0;
            }

            @Override
            public void onFinish() {
            }
        };

        ctd.start();
    }
}