SurfaceView是通过子线程来更新显示的内容,很特别,所以总结了一套标准写法
public class TestSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Runnable {
SurfaceHolder mHolder;
public TestSurfaceView(Context context) {
super(context);
}
public TestSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() { //get Holder ,监控回调
mHolder = getHolder();
mHolder.addCallback(this);
//设置可以获取焦点
setFocusable(true);
setFocusableInTouchMode(true);
//设置常亮
setKeepScreenOn(true);
}
boolean isRunning = false;
@Override
public void surfaceCreated(SurfaceHolder holder) {
//在这里开启一个线程去绘制canvas
isRunning = true;
Thread t = new Thread(this);
t.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) { //当surfaceView被销毁时会调用
isRunning = false; //这里需要终端绘制逻辑
}
@Override
public void run() {
while (isRunning) {
draw();
}
}
//这个canvas是用来绘制内容的
private Canvas canvas;
private void draw() {
try { //这个try,catch是用来防止用户切换程序后,使得线程中继续有逻辑执行,而造成一些特殊的异常
canvas = mHolder.lockCanvas();
if (canvas == null) return;
/*
这里操作canvas,具体的显示逻辑
*/
} catch (Exception e) { //由于用户已经切换程序了,所以没必要处理异常了
e.printStackTrace();
} finally { //最后解锁canvas
if (canvas != null) mHolder.unlockCanvasAndPost(canvas);
}
}
}
网友评论