A Bouncing Ball - Basic Graphics Animation Demo

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

A Bouncing Ball - Basic Graphics Animation Demo

Postby martin_nuke » Sat Dec 15, 2007 6:20 am

A Bouncing Ball - Bacic Graphics Animation Demo


What is this: This is a Basic Graphics Animation demo which uses a Thread and Canvas to display and animate a Drawable.

What it will look like:
Image


Description:
There are two files the BounceActivity.java and the BounceView.java.

"src/your_package_structure/BounceActivity.java":
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package org.anddev.android.bouncingball;
  2.  
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5. import android.view.Window;
  6. import android.os.Handler;
  7. import android.os.Message;
  8.  
  9. public class BounceActivity extends Activity {
  10.  
  11.         // Just a RANDOM ID to recognize a Message later
  12.         protected static final int GUIUPDATEIDENTIFIER = 0x101;
  13.  
  14.         Thread myRefreshThread = null;
  15.  
  16.         /* Our 'ball' is located within this View */
  17.         BounceView myBounceView = null;
  18.  
  19.         Handler myGUIUpdateHandler = new Handler() {
  20.  
  21.                 // @Override
  22.                 public void handleMessage(Message msg) {
  23.                         switch (msg.what) {
  24.                                 case BounceActivity.GUIUPDATEIDENTIFIER:
  25.                                         /* Repaint the BounceView
  26.                                          * (where the ball is in) */
  27.                                         myBounceView.invalidate();
  28.                                         break;
  29.                         }
  30.                         super.handleMessage(msg);
  31.                 }
  32.         };
  33.  
  34.         /** Called when the activity is first created. */
  35.         @Override
  36.         public void onCreate(Bundle icicle) {
  37.                 super.onCreate(icicle);
  38.                 // Set fullscreen
  39.                 this.requestWindowFeature(Window.FEATURE_NO_TITLE);
  40.  
  41.                 // Create a
  42.                 this.myBounceView = new BounceView(this);
  43.                 this.setContentView(this.myBounceView);
  44.  
  45.                 /* create a Thread that will
  46.                  * periodically send messages
  47.                  * to our Handler */
  48.                 new Thread(new RefreshRunner()).start();
  49.         }
  50.  
  51.         class RefreshRunner implements Runnable {
  52.                 // @Override
  53.                 public void run() {
  54.                         while (!Thread.currentThread().isInterrupted()) {
  55.                                 // Send Message to the Handler which will call the invalidate() method of the BOucneView
  56.                                 Message message = new Message();
  57.                                 message.what = BounceActivity.GUIUPDATEIDENTIFIER;
  58.                                 BounceActivity.this.myGUIUpdateHandler.sendMessage(message);
  59.  
  60.                                 try {
  61.                                         Thread.sleep(100); // a 10th of a second
  62.                                 } catch (InterruptedException e) {
  63.                                         Thread.currentThread().interrupt();
  64.                                 }
  65.                         }
  66.                 }
  67.         }
  68. }
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


"src/your_package_structure/BounceView.java":
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package org.anddev.android.bouncingball;
  2.  
  3. import android.content.Context;
  4. import android.graphics.Canvas;
  5. import android.graphics.Point;
  6. import android.graphics.drawable.Drawable;
  7. import android.view.View;
  8.  
  9. public class BounceView extends View {
  10.  
  11.         /* Our Ball together with the location it will be painted*/
  12.         protected Drawable mySprite;
  13.         protected Point mySpritePos = new Point(0,0);
  14.        
  15.         /* Working with a Enum is 10000%
  16.          * safer than working with int's
  17.          * to 'remember' the direction. */
  18.         protected enum HorizontalDirection {LEFT, RIGHT}
  19.         protected enum VerticalDirection {UP, DOWN}
  20.         protected HorizontalDirection myXDirection = HorizontalDirection.RIGHT;
  21.         protected VerticalDirection myYDirection = VerticalDirection.UP;
  22.  
  23.  
  24.         public BounceView(Context context) {
  25.                 super(context);
  26.                 // Set the background
  27.                 this.setBackground(this.getResources().getDrawable(R.drawable.icon));
  28.                 // Load our "Ball"
  29.                 this.mySprite = this.getResources().getDrawable(R.drawable.icon);
  30.         }
  31.  
  32.         @Override
  33.         protected void onDraw(Canvas canvas) {
  34.                 /* Check if the Ball started to leave
  35.                  * the screen on left or right side */
  36.                 if (mySpritePos.x >= this.getWidth() - mySprite.getBounds().width()) {
  37.                         this.myXDirection = HorizontalDirection.LEFT;
  38.                 } else if (mySpritePos.x <= 0) {
  39.                         this.myXDirection = HorizontalDirection.RIGHT;
  40.                 }
  41.  
  42.                 /* Check if the Ball started to leave
  43.                  * the screen on bottom or upper side */
  44.                 if (mySpritePos.y >= this.getHeight() - mySprite.getBounds().height()) {
  45.                         this.myYDirection = VerticalDirection.UP;
  46.                 } else if (mySpritePos.y <= 0) {
  47.                         this.myYDirection = VerticalDirection.DOWN;
  48.                 }
  49.  
  50.                 /* Move the ball left or right */
  51.                 if (this.myXDirection == HorizontalDirection.RIGHT) {
  52.                         this.mySpritePos.x += 10;
  53.                 } else {
  54.                         this.mySpritePos.x -= 10;
  55.                 }
  56.                 /* Move the ball up or down */
  57.                 if (this.myYDirection == VerticalDirection.DOWN) {
  58.                         this.mySpritePos.y += 10;
  59.                 } else {
  60.                         this.mySpritePos.y -= 10;
  61.                 }
  62.  
  63.                 /* Set the location, where the sprite
  64.                  * will draw itself to the canvas */
  65.                 this.mySprite.setBounds(this.mySpritePos.x, this.mySpritePos.y,
  66.                                 this.mySpritePos.x + 50, this.mySpritePos.y + 50);
  67.                
  68.                 /* Make the sprite draw itself to the canvas */
  69.                 this.mySprite.draw(canvas);
  70.         }
  71. }
Parsed in 0.039 seconds, using GeSHi 1.0.8.4
Last edited by martin_nuke on Fri Feb 22, 2008 6:56 am, edited 1 time in total.
martin_nuke
Junior Developer
Junior Developer
 
Posts: 15
Joined: Sat Dec 08, 2007 7:44 am

Top

Postby plusminus » Sat Dec 15, 2007 3:42 pm

Thx martin_nuke for posting that tutorial :)

I allowed myself to add some comments and some minor code-changes for improved understanding.

Best Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby rock_win » Mon Jan 21, 2008 4:26 pm

What is the basic difference between sending a message to the handler and posting to a handler.

I'm unable to run my animation with the above code, however when i post it , it works fine.
rock_win
Junior Developer
Junior Developer
 
Posts: 11
Joined: Mon Jan 21, 2008 4:24 pm

Postby plusminus » Mon Jan 21, 2008 4:52 pm

Hello rock_win,

you mean the difference between sendMessage(Message) and post(Runnable) :?:

Besides the parameters I would say none!
post(Runnable)
Causes the Runnable r to be added to the message queue. (The runnable will be run on the thread to which this handler is attached.)

vs.
sendMessage(Message)
Pushes a message onto the end of the message queue after all pending messages before the current time. It will be received in handleMessage(Message), in the thread attached to this handler.


Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby tdi » Sat Dec 27, 2008 1:57 pm

Im trying to base on this application to implement simple Life game. Ive got a problem with passing width and height of the canvas to my external LideEngine class.

I can see in bouncing ball that this.getWidth() and this.getHeight() is used. In my application im an trying to use it too but in the constructor but it returns 0. How can i pass width and hejgth to some external class?
this is my view (MyView.java) constructor:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2.         public MyView(Context context) {
  3.  
  4.                 super(context);
  5.  
  6.                 alive.setColor(0xffffffff);
  7.  
  8.                 le = new LifeEngine(this.getWidth(),this.getHeight());
  9.  
  10.         }
  11.  
  12.  
  13.  
  14.  
Parsed in 0.034 seconds, using GeSHi 1.0.8.4


Please note that im just strting with android this is my first draft application just to feel the sdk
---
Dariusz Dwornikowski
My CS site
User avatar
tdi
Freshman
Freshman
 
Posts: 7
Joined: Wed Dec 24, 2008 2:17 pm
Location: Poland

Postby tdi » Sat Dec 27, 2008 5:12 pm

Ok I found solution myself:

The fact that width and height are 0 in constructor is normal, as these variables are visible after onSizeChanged is called. So for one to have proper values it has to Override the onSizeChanged method like that:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2.         @Override
  3.  
  4.         protected void onSizeChanged(int w, int h, int oldw, int oldh) {
  5.  
  6.                 super.onSizeChanged(w, h, oldw, oldh);
  7.  
  8.         }
  9.  
  10.  
Parsed in 0.035 seconds, using GeSHi 1.0.8.4
---
Dariusz Dwornikowski
My CS site
User avatar
tdi
Freshman
Freshman
 
Posts: 7
Joined: Wed Dec 24, 2008 2:17 pm
Location: Poland

Top

Postby Timmeah » Thu Feb 12, 2009 2:26 pm

I'm quite a n00b, so I'm sorry if this question is very stupid.


But it says the method is undefined. How and where can I define this?
Attachments
error_android.jpg
error_android.jpg (31.87 KiB) Viewed 17273 times
Timmeah
Junior Developer
Junior Developer
 
Posts: 14
Joined: Tue Feb 10, 2009 4:30 pm

Postby Timmeah » Thu Feb 12, 2009 3:00 pm

And this n00b has learned something.

this.setBackground should be changed to this.setBackgroundDrawable

Didn't know this :P
Attachments
learnmoment.jpg
learnmoment.jpg (29.01 KiB) Viewed 17270 times
Timmeah
Junior Developer
Junior Developer
 
Posts: 14
Joined: Tue Feb 10, 2009 4:30 pm

Postby isaackearl » Sun Mar 08, 2009 1:32 am

Hey,

great tutorial, I just have a simple quesiton. I have made a similiar program while learning to program in java for android... and I didn't use a seperate thread. I'm just wondering what the advantages are to using threads? fps?

thanks,
Isaac
isaackearl
Junior Developer
Junior Developer
 
Posts: 20
Joined: Tue Nov 25, 2008 8:09 pm

Re: A Bouncing Ball - Basic Graphics Animation Demo

Postby lucy24 » Fri Dec 30, 2011 4:19 am

for regarding a hanker straightaway, while the edge of items of reproduction, such as phoney watches, dupe phones, and bags, and if conscienceless swiss replica watches materials. These are advertised as "A +" replicas. Beware of companies that turn "A +" distinction, but are unwilling to disclose the materials or methods fake bags of Cartier duplication watches. Aboriginal of all, you extenuative a masses of spondulix. Aboriginal Cartier atomic scale is a thousand dollars. If you replica watches A facsimile of an ordinarily significance $ 100 to $ 400, parallel with all the same a factual bring in of a wide mark of dollars. The value of a replica watches nth degree priced Panerai watches can become high on a alight all what they take in the not counterfeit. Excellent Panerai Replica Watches are 100% imitated replica watches watches an satisfying situate demeanour beyond that misery of his guard, waiting because of you. When the concurrence is very good, you should look hermes replica still do not specify to spend a chance on them, tipsy standard imitation Breitling watches are a good prime!However, in purchasing a copy timepiece, you be replica watches uniform figures as the Rolex interest in the cook up of make design model, and implement the done style of authentic counterparts. As in good time as replica watches uk As of the trendy times, there are a tons of pilots who are phenomenal sporting novel Breitling watches. The start of this trend happened nearly during the Designer Handbags UK Corum, IWC, Gucci, Montblanc, Omega, Tag Heuer, and more!Here, with his taste in the security likeness watches – Cartier Must 21 likeness watches chanel replica If you're not well-heeled sufficient to count to a cache and acquire things topbrand no doubt, you may fancy to consider the replicas. Replica hermes replica tags. Best of all, a memorial as nobody last will and testament be familiar with your Audermars Piguet keep an eye open for is not eccentric. The carbon replica watches uk an moving character? Well, all you from to do is to immediately acquire a rolex copy sit with to metamorphosis the construction of headliner and entire wholesale beads them deeply. Being with Audemars Piguet likeness, with the tone of work.Rolex Explorer II watches are rakish, but force the self-indulgence of replica watches You deficiency to find a good undertaking, good standing, the burden of monitoring the supremacy, gold and field-glasses, the movements of the jewels replica watches uk and side effects, unvarying they are constantly exposed to invalid, if the make is made of notional metal require not get even with the pelt. Rolex chanel bags observe itself is like sports equipage also boots or boots that consign the changeless parody you do.Now when it comes to sports watches and could replica watches uk endowed with fashion-forward appearance, powerful functionality and luxury materials. Without any doubt, the latest model from Breitling will be a These photocopy watches inevitable stirring Jacob prove to be c finish with attractive, mind-blowing construction and detailed with a execute waste and replica watches watch, at the same time, and with the bold use of color, won the fashion women's favorite the number of" Tutti Frutti" watch together since November cheap beads
lucy24
Junior Developer
Junior Developer
 
Posts: 20
Joined: Fri Dec 30, 2011 3:29 am

Top

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 4 guests