Search code examples
javaandroidtouch-event

OnTouchEvent in different class than the main


Is this possible, to make an OnTouchEvent method in class other than for example public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback? I mean, that's my main class, where everything happens. I tried with listeners, but can't get them working at all...

I just need to create a totally separate class for touch events. For sensors it worked by passing the Sensor object from MainActivity into the SurfaceView.


Solution

  • Yes. You can set OnTouchListener on any class that inherits View with the setOnTouchListener() method.

    You can make it to be separate class that implements View.OnTouchListener.

    public class MyTouchListener implements View.OnTouchListener
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            // your code goes here
            return false;
        }
    }
    

    then

    myView.setOnTouchListener(new MyTouchListener());