In our retro squash game, we will have no UI buttons, so we cannot use the OnClickListener
interface and override the onClick
method. This is not a problem, however. We will just use another interface to suit our situation. We will use OnTouchListener
and override the onTouchEvent
method. It works a bit differently, so let's take a look at implementing it before we dive into the game code.
We must implement the OnTouchListener
interface for the activity we want to listen to touches in, like this:
public class MainActivity extends Activity implements View.OnTouchListener{
Then we can override the onTouchEvent
method, perhaps a bit like this.
@Override public boolean onTouchEvent(MotionEvent motionEvent) { float x = motionEvent.getX(); float y = motionEvent.getY(); //do something with the x and y values return false; }
The x
variable will hold the horizontal value of the position on the screen that was touched, and y
will hold the vertical position. It is...