我想每100毫秒或按下一个按钮时重复绘制一些东西。对于按钮onclick事件,它工作正常,但我不能使它在一个线程中工作。以下是代码:
的onclick
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Draw();
}
});
螺纹
private Handler handler = new Handler();
private Runnable runnable = new Runnable()
{
public void run()
{
Draw();
handler.postDelayed(this, 1000);
}
};
绘制方法
private void Draw(){
Paint paint = new Paint();
int i;
Canvas canvas = holder.lockCanvas();
// Dibujo el fondo
paint.setColor(getResources().getColor(android.R.color.black));
canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), paint);
holder.unlockCanvasAndPost(canvas);
}
答案 0 :(得分:0)
这是因为UI线程单独运行到Runnable
线程。像这样的单独线程无法进行交互。您将需要使用AsyncTask
线程,这将使您能够定期访问UI线程。
例如:
private class ExampleThread extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {}
@Override
protected void doInBackground(Void... params) {
while(!isCancelled()) { // Keep going until cancelled
try {
Thread.sleep(100); // Delay 100 milliseconds
} catch (InterruptedException e) {
Thread.interrupted();
}
publishProgress(); // Run onProgressUpdate() method
if(isCancelled()) break; // Escape early if cancel() is called
}
}
@Override
protected void onPostExecute(Void... params) {}
@Override
protected void onProgressUpdate(Void... params) {
// Here you can access the UI thread
Draw();
}
}
启动帖子:
ExampleThread thread = new ExampleThread();
thread.execute();
停止线程:
thread.cancel();
可以在this question上找到有关AsyncTask的更多信息和示例。