Android SurfaceView Moving Rectangle Tutorial

SurfaceView is a custom view that able to update the GUI rapidly such as rendering the animation in the activity. Android view is different with surfaceView which cannot update the GUI. When we need to use surfaceview? We can use the surfaceView with camera or playing the video. Besides that, we also can use canvas to draw image every second and update the GUI so the image will be look like its moving on. In this tutorial, I will teach you how to use android surfaceview and draw a rectangle on it to keep update it every second.

 

Creating a New Project

1. Open Android Studio IDE in your computer.
2. Create a new project and Edit the Application name to “SurfaceViewExample”.
(Optional) You can edit the company domain or select the suitable location for current project tutorial. Then click next button to proceed.
3. Select Minimum SDK (API 15:Android 4.0.3 (IceCreamSandwich). I choose the API 15 because many android devices currently are support more than API 15. Click Next button.
4. Choose “Empty Activity” and Click Next button
5. Lastly, press finish button.

 

Edit MainActivity.java class

After create your project, go to the mainactivity.java class and copy paste the source code in the bottom. In this class I will add one more class which name “RectangleView” and extends it to SurfaceView and implements SurfaceHolder Callback. When the SurfaceView is created, I will start the timer and it will be stop the timer when surfaceview is destroyed.

For the timer schedule, I set the delay and period to 100 milliseconds which is 0.1 seconds.

In the draw() method, I draw the rectangle which has 100 width and height and updating the rectangle by adding y-axis which is vertical.

Run Your Project

In conclusion, now you can run this project to see what will be happen in your activity. You will see the rectangle moving down every 0.1 seconds.

 

(Android SurfaceView Moving Rectangle)

Source Code

(Visited 4,015 times, 1 visits today)
Advertisements

Yong Loon Ng

Ng Yong Loon, better known as Kristofer is a software engineer and computer scientist who doubles up as an entrepreneur.

You may also like...

1 Response

  1. Giridhar says:

    Here we have only one image and one direction, if there are multiple, images and multiple different directions for each image, how can we do this.
    I came to this tut for changing the bitmap drawn on an image every second

Leave a Reply

Your email address will not be published. Required fields are marked *