假设我想绘制一条线,然后等待五秒钟,然后绘制另一条线.我有这样的方法:
    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);
    }
我该如何暂停?
你可以像这样使用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();
    }
问候,
不要在 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);
    }
}
比在你的代码中使用它像这样
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);
| 归档时间: | 
 | 
| 查看次数: | 12723 次 | 
| 最近记录: |