Android之surfaceview倒计时
时间: 2023-08-05 10:47:18 浏览: 93
Android倒计时
要在 Android 的 SurfaceView 中实现倒计时功能,您需要创建一个线程,该线程在 SurfaceView 上绘制计时器并更新计时器的值。以下是一个简单的示例,您可以参考:
```java
public class CountdownSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private CountdownThread mThread;
private int mCountdownValue = 10; // 倒计时的初始值
public CountdownSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
mHolder = getHolder();
mHolder.addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mThread = new CountdownThread(mHolder, mCountdownValue);
mThread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
mThread.setRunning(false);
while (retry) {
try {
mThread.join();
retry = false;
} catch (InterruptedException e) {
// 重试
}
}
}
private class CountdownThread extends Thread {
private SurfaceHolder mThreadHolder;
private int mCountdownValue;
private boolean mIsRunning = true;
public CountdownThread(SurfaceHolder holder, int countdownValue) {
mThreadHolder = holder;
mCountdownValue = countdownValue;
}
public void setRunning(boolean isRunning) {
mIsRunning = isRunning;
}
@Override
public void run() {
while (mIsRunning) {
Canvas canvas = null;
try {
canvas = mThreadHolder.lockCanvas();
synchronized (mThreadHolder) {
drawCountdown(canvas);
Thread.sleep(1000); // 每秒钟更新一次计时器
mCountdownValue--;
if (mCountdownValue == 0) {
break; // 计时器结束
}
}
} catch (InterruptedException e) {
// 重试
} finally {
if (canvas != null) {
mThreadHolder.unlockCanvasAndPost(canvas);
}
}
}
}
private void drawCountdown(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(100);
canvas.drawColor(Color.BLACK);
canvas.drawText(String.valueOf(mCountdownValue), getWidth() / 2, getHeight() / 2, paint);
}
}
}
```
在这个例子中,我们创建了一个 CountdownSurfaceView 类,它继承自 SurfaceView,并实现了 SurfaceHolder.Callback 接口。在 surfaceCreated() 方法中,我们创建了一个 CountdownThread 线程,并启动该线程。在 CountdownThread 线程中,我们使用 Canvas 绘制计时器,并使用 Thread.sleep() 方法使线程休眠一秒钟。每次线程醒来时,我们更新计时器的值,并检查计时器是否结束。如果计时器结束,我们退出线程。最后,在 surfaceDestroyed() 方法中,我们停止线程并等待线程结束。
请注意,在这个例子中,我们将计时器的值绘制在 SurfaceView 的中心。您可以根据自己的需要更改这个位置。
阅读全文