在Android studio中使用SurfaceView的onTouchEvent方法需要先定义SurfaceView,并为其添加相关的SurfaceHolder.Callback方法,然后再重写onTouchEvent方法,实现对SurfaceView的手势操作响应。
具体步骤如下:
private SurfaceView mSurfaceView;
private SurfaceHolder mHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSurfaceView = findViewById(R.id.surfaceView);
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
//SurfaceView创建成功回调,进行初始化操作
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
//SurfaceView大小发生改变回调,进行更新操作
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
//SurfaceView销毁回调,进行资源释放操作
}
});
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//按下事件处理
break;
case MotionEvent.ACTION_MOVE:
//移动事件处理
break;
case MotionEvent.ACTION_UP:
//抬起事件处理
break;
}
return super.onTouchEvent(event);
}
这样就可以在Android studio中使用SurfaceView的onTouchEvent方法啦。