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

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

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线程中调用,你将阻止它。 使用标志来处理将绘制的行

 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 task = new AsyncTask() { @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); 

你可以像这样使用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(); } 

问候,

嗯…你可以设置一个标志(在其他方法中)和你的onDraw()的标志,根据该标志的值绘制该行。

也许是类似的东西(虽然我不知道为什么你需要暂停)

 invalidate(); pause/sleep(); //set flag invalidate(); 

使用Thread.sleep(5000) ,应该这样做。