如何绘制接下来的事情,在Android上之前暂停5秒? [英] How to pause for 5 seconds before drawing the next thing on Android?

查看:152
本文介绍了如何绘制接下来的事情,在Android上之前暂停5秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我要画一条线,然后等待五秒钟,然后绘制另一条线。我有这样一个方法:

Say I want to draw a line, then wait five seconds, then draw another line. I have a method like this:

    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);
    }

如何暂停?

推荐答案

不要在OnDraw的方法,等待它被称为在UI线程,你会阻止它。使用标志来处理该线将被绘制

Don't wait in onDraw method it's called in the UI thread and you'll block it. Use flags to handle which line will be drawn

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);
    }
}

不是用它在你的code这样

Than use it in your code like this

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);

这篇关于如何绘制接下来的事情,在Android上之前暂停5秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆