SurfaceView使用总结
一,简单使用
比如点击view时需要它重画
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
mXCross = event.getX();
mCrossEnabled = true;
// 重绘
if(myThread!=null && myThread.myHandler != null) {
myThread.myHandler.sendEmptyMessage(0);
}
// Log.e("on mXCross,mYCross==",mXCross + "," + mYCross);
break;
case MotionEvent.ACTION_UP :
mXCross = -1f;
mCrossEnabled = false;
// 重绘
if(myThread!=null && myThread.myHandler != null) {
myThread.myHandler.sendEmptyMessage(0);
}
break;
}
return true;
}
在子线程中绘制View,需要线程绑定一个Looper,需要handler
// 线程内部类
class MyThread extends Thread {
private SurfaceHolder holder;
private StockDrawWave drawWave;
MyHandler myHandler;// 用户子线程绘制UI
public MyThread(SurfaceHolder holder, StockDrawWave drawWave) {
this.holder = holder;
this.drawWave = drawWave;
}
class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
drawTimeChar();// 以后刷新时都直接执行绘制方法
}
}
@Override
public void run() {// 此处为初始化,第一次绘制时运行
Looper.prepare();// Looper与Thread绑定
myHandler = new MyHandler();// 与Looper绑定
drawTimeChar();
Looper.loop();// 处理消息
}
View关闭时,终止线程并让其被回收
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (myThread != null) {
myThread.isRun = false;
myThread.myHandler.getLooper().quit();// 终止looper循环,让线程可以被回收
myThread = null;
}
}