问题
I am trying to get a simple surface view to respond to touch events. The application below launches but does not respond to touch events. I have a Log.i statement to confirm (by printing to the console) whether or not the touch event is working. Can anyone tell me what I am doing wrong?
This is the my main activity
public class MainActivity extends Activity {
public static int screenWidth, screenHeight;
public static boolean running=true;
public static MainSurface mySurface;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this gets the size of the screen
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
screenWidth = displaymetrics.widthPixels;
screenHeight = displaymetrics.heightPixels;
Log.i("MainActivity", Integer.toString(screenWidth) + " " + Integer.toString(screenHeight));
mySurface = new MainSurface(this);
setContentView(mySurface);
}
}
This is the surface view class
public class MainSurface extends SurfaceView implements OnTouchListener {
public MainSurface(Context context) {
super(context);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
int point = event.getPointerCount();
Log.i("MainSurface", Integer.toString(x)); //nothing prints to the console here
return true;
}
}
回答1:
- Remove
implements OnTouchListener
. - Change
onTouch(View v, MotionEvent event)
toonTouchEvent(MotionEvent event)
.
The reason it's not working is that the SurfaceView doesn't know that it is supposed to be it's own OnTouchListener without you telling it. Alternatively, you could make it work by adding this code to your onCreate():
mySurface = new MainSurface(this);
mySurface.setOnTouchListener(mySurface);
However since SurfaceView already has an OnTouchEvent function, it's simpler to just use that.
Also, don't declare your SurfaceView as static.
回答2:
You should identify Action
in touch Event like:
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch(action){
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_CANCEL:
break;
case MotionEvent.ACTION_OUTSIDE:
break;
}
return true;
}
来源:https://stackoverflow.com/questions/28979683/android-surfaceview-not-responding-to-touch-events