1

我正在尝试实现一个交通信号灯,它将颜色从红色变为绿色,然后变为黄色。为此,我使用了一个按钮,并将按钮的背景更改为受尊重的颜色。我正在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();
    }
}

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

4

1 回答 1

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();
    }
}
于 2013-07-21T08:00:01.823 回答