Android SurfaceView not responding to touch events

被刻印的时光 ゝ 提交于 2020-01-04 15:28:23

问题


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:


  1. Remove implements OnTouchListener.
  2. Change onTouch(View v, MotionEvent event) to onTouchEvent(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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!