Handling touches
In our Pong game, we will have no UI buttons, and therefore 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 little bit differently, so let's take a look before we dive into the game code.
We must implement the OnTouchListener
interface for the activity we want to listen for 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 variable x
will hold the horizontal value of the position on the screen that was touched, and y
will hold the vertical position. It is worth noting...