如何在Android上绘制下一个东西之前暂停5秒?

Kal*_*ina 5 android draw wait

假设我想绘制一条线,然后等待五秒钟,然后绘制另一条线.我有这样的方法:

    public void onDraw(Canvas canvas) {
        int w = canvas.getWidth();
        int h = canvas.getHeight();
        canvas.drawLine(w/2, 0, w/2, h-1, paint);
        // PAUSE FIVE SECONDS
        canvas.drawLine(0, h/2, w-1, h/2, paint);
    }
Run Code Online (Sandbox Code Playgroud)

我该如何暂停?

Hou*_*ine 6

你可以像这样使用CountDownTimer:

public void onDraw(Canvas canvas) {
        int w = canvas.getWidth();
        int h = canvas.getHeight();
        canvas.drawLine(w/2, 0, w/2, h-1, paint);
        // PAUSE FIVE SECONDS
        new CountDownTimer(5000,1000){

            @Override
            public void onTick(long miliseconds){}

            @Override
            public void onFinish(){
               //after 5 seconds draw the second line
               canvas.drawLine(0, h/2, w-1, h/2, paint);
            }
        }.start();

    }
Run Code Online (Sandbox Code Playgroud)

问候,


Moj*_*sin 2

不要在 UI 线程中调用 onDraw 方法中等待,否则您将阻止它。使用标志来处理将绘制哪条线

boolean shouldDrawSecondLine = false;

public void setDrawSecondLine(boolean flag) {
    shouldDrawSecondLine = flag;
}

public void onDraw(Canvas canvas) {
    int w = canvas.getWidth();
    int h = canvas.getHeight();
    canvas.drawLine(w/2, 0, w/2, h-1, paint);
    if (shouldDrawSecondLine) {
        canvas.drawLine(0, h/2, w-1, h/2, paint);
    }
}
Run Code Online (Sandbox Code Playgroud)

比在你的代码中使用它像这样

final View view;
// initialize the instance to your view
// when it's drawn the second line will not be drawn

// start async task to wait for 5 second that update the view
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
    @Override
    protected Void doInBackground(Void... params) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        view.setDrawSecondLine(true);
        view.invalidate();
        // invalidate cause your view to be redrawn it should be called in the UI thread        
    }
};
task.execute((Void[])null);
Run Code Online (Sandbox Code Playgroud)