User Touch Handling On Sprite In Android

In this example we will implement onTouchEvent() to handle user touch on SurfaceView. When user touch on the screen(SurfaceView), it will call setX(x) and setY(y) of mySprite object to update its position.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it UserTouchOnSurfaceView.

2.) Write following into main.xml:

 

 

 

3.) Create and write following into GameThread.java:

 

 

4.) Create and write following into GameSurface.java:

 

 

 

5.) Create and write following into ForegroundSurface.java:

 

 

 

6.) Create and write following into SpriteExample.java:

 

 

 

7.) Write following permissions to your manifest

 

 

8.) Run for output.

Steps:

1.) Create a project named UserTouchOnSurfaceView and set the information as stated in the image.

Build Target: Android 4.4
Application Name: UserTouchOnSurfaceView
Package Name: com.example.UserTouchOnSurfaceView
Activity Name: UserTouchOnSurfaceViewActivity

touch1

2.) Open UserTouchOnSurfaceViewActivity.java file and write following code there:

 

 

 

3.) Compile and build the project.

Output

touch2