我想每秒更改一次绘图

时间:2018-12-15 17:23:40

标签: android

我正在制作一个每秒变化的信号灯程序。 我正在使用Canvas。 颜色应从红色变为黄色,从黄色变为绿色,从绿色变为红色。 它会不断重复执行此操作。这是无效的代码。

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    DrawView drawview = (DrawView) findViewById(R.id.dv);

    while(true)
    {
        SystemClock.sleep(1000);
        drawview.color1 = Color.RED;
        drawview.color2 = Color.BLACK;
        drawview.color3 = Color.BLACK;

        SystemClock.sleep(1000);
        drawview.color1 = Color.BLACK;
        drawview.color2 = Color.YELLOW;
        drawview.color3 = Color.BLACK;

        SystemClock.sleep(1000);
        drawview.color1 = Color.BLACK;
        drawview.color2 = Color.BLACK;
        drawview.color3 = Color.GREEN;
    }
}

}

1 个答案:

答案 0 :(得分:0)

您的代码不起作用,因为您停止了程序的运行。 当您从活动SystemClock.sleep(1000)调用onCreate时,冻结了应用程序的UI线程,因此屏幕上没有任何显示。

如果您希望您的应用每秒自动执行某项操作,请设置一个TimerTask

但是请注意,此任务将在后台线程中运行,因此要更新UI,您将需要使用runOnUiTHread

这里是一个例子:

public class MainActivity extends AppCompatActivity {
    private Timer drawTimer; //keep your timer, you will need to cancel the task before ending your app

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        drawTimer = new Timer(); //create the timer once your app starts
    }

    @Override
    protected void onResume() {
        drawTimer.schedule(new UpdateDrawing(), 1000, 1000); //schedule your task to run every second
    }

    @Override
    protected void onPause() {
        drawTimer.cancel(); //stop the task if app is closed or goes to background
    }

    //here is how your task class would look:
    private class UpdateDrawing extends TimerTask {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //Do color change here
                }
            });
        }
    }
}