Note: This article is really old. It is here for posterity only. You should really find a more current tutorial.
I’ve been a little frustrated by the lack of Android tutorials. I got a Hello world going, and found that most of the few tutorials I could find were WAY more complicated than what I want to start with. GPS, map overlays, to-do lists, etc, which is great and all but I want to start simple and work up from that. So I set out to build “Hello Circle,” a program which drew a dot on the screen wherever you touched it. After about 12 hours of beating my head against Eclipse, the Android SDK, and the frequently incorrect Android documentation I got it working. So here’s a tutorial.
Setting up the environment I’m going to assume you already successfully completed the Hello World tutorial. Which means you’ve got yourself an IDE (probably Eclipse), the Android SDK, and the ADK (Android Development Kit) which is a plugin for Eclipse to help keep things in order. If you haven’t done that yet follow these instructions and pray everything works as planned. I’ll see you in a few hours. Create a project just like you did for Hello World. Creating the ViewGroup In order for anything to display on the screen you need to create a view. In the Hello World tutorial you created a TextView. We’re going to use the XML setup for creating our view, and rather than creating a TextView we’re going to use a FrameLayout, which is acutlaly a view group. Open up /res/layout/main.xml and plop in this fine code (obliterating anything that may be there):
This, when it’s called in our code, will create a FrameLayout view with an id of “main view,” a width/height that fills the screen, and a neon green background. The hex color code for the background includes the alpha channel (the first to FFs). Setting the contentView to our XML Head over to your main class and call setContentView on your layout. Your code should look something vaguely like this:
import android.app.Activity;
import android.os.Bundle;
public class RoboTown extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
If you run your code at this point you should get a big green background which does nothing. Hooray! Creating the Ball class Now we want to create a circle. Actually we want to create a lot of circles. So the first step is to create a new class called Ball. Right click on your project’s main class in the Package Explorer (on the left) and click New > Class. Give it the name Ball and click Finish. Our ball is actually going to be another view. What? Yeah. It’s a view. All of our Ball views will eventually go into our FrameLayout, but we’ll worry about that later. So first, modify your Ball class so that it extends View, since it’s a new type of View, and while you’re at it go ahead and import some of the things we’ll need for drawing:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
public class Ball extends View {
}
In order to draw a ball we need a handful of things: a Canvas to draw them on, x and y coordinates to place the center of the ball, the radius, and Paint to give it color. So we’ll start by establishing those (I hid the imports for the sake of clarity, you should leave yours there):
public class Ball extends View {
private final float x;
private final float y;
private final int r;
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
In the last line we create a new Paint object, creatively called mPaint. A Paint contains information like colors, text sizes, etc, which affect the appearance of the drawing. So far we haven’t assigned any of those things to the Paint, we’ve just created it. Now we need to write the Ball constructor, which is the method to be called whenever we create a new ball:
private final int r;
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public Ball(Context context, float x, float y, int r) {
super(context);
mPaint.setColor(0xFFFF0000);
this.x = x;
this.y = y;
this.r = r;
}
}
Our constructor takes a Context, x, y, and radius r. We pass these arguments in when we instantiate the object and assign them to the object properties. And lastly, the method which actually draws the circle, onDraw:
public Ball(Context context, float x, float y, int r) {
super(context);
mPaint.setColor(0xFFFF0000);
this.x = x;
this.y = y;
this.r = r;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, r, mPaint);
}
Ok, our Ball class is done. Save it and head back over to the main class. Drawing a Ball on the screen At this point we haven’t actually drawn anything. We’ve just created Ball which we *could* draw if we so desired. In order to draw it on the screen we first have to get a hold of our FrameLayout. Since we created it via XML we’ll need to find it again using findViewById():
setContentView(R.layout.main);
FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
Now we can use the addView method to attach a new Ball to our main view:
FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
main.addView(new Ball(this,50,50,25));
Run your code now and, if all goes well, you’ll have a circle with a radius of 25 pixels in the upper left corner of the screen. Yay! Take some time to play around with Paint options, positioning, etc with the various methods outlined in the documentation. Now all we have to do is add a touch listener to react when the screen is touched. Which is thankfully pretty easy. We’re going to create a new touch listener and attach it to our main view all in one fell swoop:
main.addView(new Ball(this,50,50,25));
main.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent e) {
}
});
The onTouch() method is a callback function which will be hit whenever you touch the screen. Android will send it a View (v) and a MotionEvent (e). We already know what a view is, and a MotionEvent is an object containing information about the touch. All we care about are the X and Y coordinates, which are accessible via the getX() and getY() methods.
main.addView(new Ball(this,50,50,25));
main.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent e) {
float x = e.getX();
float y = e.getY();
}
});
The last thing we have to do before we can start drawing is to cast the view we were sent as a FrameLayout, so we can use the addView() method with it. Then we can instantiate a new Ball at the coordinates sent in the Motion Event:
main.addView(new Ball(this,50,50,25));
main.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent e) {
float x = e.getX();
float y = e.getY();
FrameLayout flView = (FrameLayout) v;
flView.addView(new Ball(getParent(), x,y,25));
}
});
The getParent() call sets the context for the Ball to the main Activity. I only vaguely understand why it has to be done this way. So now, the moment of truth! You should have all the code you need to run the app in your emulator or even on a real phone. Touching the screen will place a dot where you touched. Amazing! Hopefully you now have enough of an idea of how all this stuff plays together that you can forge your way to making something vaguely useful (which this isn’t).
Thank you. Working my way up is exactly what I like to do and so your tutorial is greatly appreciated. 🙂
Oh, and another tutorial would of course be super fantastic. 🙂
I was having trouble getting past the part where you add line 11. I was getting an error “FrameLayout cannot be resolved to a type.”
To fix it, I pressed ctl+shift+O and it automatically added an import line reading: “import android.widget.FrameLayout;”
Then, later I ran into a very similar problem when adding the touch listener. I hit ctl+shift+O again and it added two more imports: “import android.view.MotionEvent;” and “import android.view.View;”.
The final error I got was due to the onTouch function not returning a boolean value. To fix it, I added “return false;” to the end right after the flView.addView.
I’m not sure why I got those errors (maybe different version of Eclipse?). But it is all working now!
Despite the errors I got, I still think the tutorial is really great! Thanks!
Try to add
import android.view.MotionEvent;
import android.widget.FrameLayout;
Thanx a lot , I was getting those errors
thanks very much! This is the first good tutorial which I find 🙂
Excellent tutorial ! Nice style of writing ! keep it up !
Only a beginner, I got to the green screen okay, but was not able to get past this part:
setContentView(R.layout.main);
FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
main.addView(new Ball(this,50,50,25));
Where (in what segment) do you add these lines?
I tried adding them at the end of Ball.java, it says “the Constructor ball is undefined” and when I added it to Circles.java, it says “Ball cannot be resolved to a type.”
Any help is greatly appreciated!
@Lindsey,
in main Activity in onCreate method.
public class HelloCircle extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
main.addView(new Ball(this,50,50,25));
nice tut, thx!
Why you don’t have return statement in onTouch method? its boolean.
Hi,
I ask the same question that p47
Why we don’t return a boolean in the onTouch method ?
Eclipse don’t compile the example without return statement
I have try to add return true and return false.
The both solutions works but I don’t understand why.
Are you know why ?
Emeric
If you set the method to return false, then the touch event will end immediately. This means that you will draw a circle and that’s that.
If you set it to true, then the touch event will continue. This means that you can drag your finger across the screen to create a line!
I set mine to return true.
here’s the full description of the true/false return option:
onTouch() – This returns a boolean to indicate whether your listener consumes this event. The important thing is that this event can have multiple actions that follow each other. So, if you return false when the down action event is received, you indicate that you have not consumed the event and are also not interested in subsequent actions from this event. Thus, you will not be called for any other actions within the event, such as a finger gesture, or the eventual up action event.
Superb.
Covers many advanced object oriented programming concepts and technical fundamentals in a nicely laid out and methodical manner.
Very well managed concept of breaking down OOP and accessing one of the more critical aspects of utilizing the touch screen as a valid resource.
You successfully tacled the two largest obstacles that anyone engaging Android will face outside of networked or 3D application systems design.
Can’t say enough — exquisite. Keep it up. There is no substitute for knowledge and you are, without a doubt, within that ascertion’s domain.
Thanks for taking the time and making the effort to enlighten us all.
How about clicking the screen, rather than touching?
Is is still the onTouch method?
Thanks.
Not sure what you mean by clicking, do you mean by navigating with the trackball?
I haven’t done much with the trackball because I find it inconvenient, but you could try it and see!
I would like to add that if you don’t want to have a lot of circle on your screen everytime you touch it, but just “move” your circle, you can do like this:
– create a variable “public Ball mBall;” on RootTown class
– then mBall = new Ball(…); main.addView(mBall);
– on the touch method, just do this: mBall.setCoordinate(x,y); mBall.invalidate();
– On Ball class, add this method:
public void setCoordinate(float mx, float my){
this.x = mx;
this.y = my;
}
so it’s done 🙂
This works perfectly! Can you use this invalidate() method to animate a bouncing ball without the user clicking? I think I can make a game out of this! Thanks
What exactly does the mBall.invalidate() method do…why can’t it run without it?
I’m such a noob any help would be appreciated
Thank you soooooo much!
I am getting error in this part……..
public void setCoordinate(float mx, float my){
this.x = mx;
this.y = my;
}
like===The final field Ball.x cannot be assigned
The final field Ball.y cannot be assigned
I wanted to thank you as well for putting this up. I ran into the exact issues that you did. Hello World just didn’t cut it and your tutorial here has opened up the world for me. Thank you!
I’m such a java noob, but I’m trying to learn the basics to program some stuff for android. This tutorial is great: it explains things really well. However, I am having trouble when trying to compile the source code. Can anyone help? Here is my source for the main class:
package com.mpruitt105.drawcircle;
import android.app.Activity;
import android.os.Bundle;
public class DrawCircle extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
main.addView(new Ball(this,50,50,25));
}
}
It has 2 errors that both say ‘FrameLayout cannot be resolved to a type’
Does anyone know what the heck that means? I’m so lost. Thanks 🙂
You need to import the FrameLayout widget.
Add import android.widget.FrameLayout to the top of your code.
I think there are a few other imports I forgot to list. The editor I was using adds them automagically.
Thanks, it worked 😀 Now I’m gonna figure out how to get it to constantly draw, like a paint program.
Very Nice!… Develop more application like this!…………….
I think you forgot to “return true;” in function onTouch.
Thank you very much! You were a great help!
Greetz!
Since i used the onTouch there is the following errors;
[2009-12-29 18:48:07 – Robotown]Failed to upload Robotown.apk on device ’emulator-5554′
[2009-12-29 18:48:07 – Robotown]java.io.IOException: Unable to upload file: Local file doesn’t exist.
[2009-12-29 18:48:07 – Robotown]Launch canceled!
anyone knows what cause this? 🙁
i get this error:
the application xxx-xxx has stopped unexpectedly. please try again.
then i click on Force Close
i have the same code. any insight?
nevermind.. i found the error! lol
i forgot to instantiate the Paint class.. tadaaaaaaa!!!
Great Tutorial, Thanks a lot !
Cool tutorial. If only the android.com site could have examples like this!
I’m wondering how to NOT have it keep creating balls when you touch and then drag your finger across the screen?
Thanks a lot !
How do you fill this circle with an image ?
very good – thanks – gonna do any more android tutorials?
Thanks a lot! 🙂
This tutorial ROCKS!!! Please provide more tutorials : )
Great Tut!.. simple and clear, thanks a lot 🙂
Cracking tutorial, i’ve been looking for a good FrameLayout tutorial for a while, this one is excellant.
cheers 🙂
Very nice tutorial! Like others, I had problems with some of the imports not being found, but once I got those added, it works perfectly!
I am now going to try to add sound to this, so that when you touch the screen, it draws a circle and makes a sound…
Hello,
Please tell how to get touchlistner for bitmap object witch is animating inside the canvas, i want to stop by touching it and then want to drag wherever i want in the screen. please tell me its urgent.
thanks.
this is so helpful thank you thank you thank you thank you thank you!!
hmmm getParent() is indeed a strange thingy , tell me if you don’t understand it , how did you come up with it ?
Thank you for putting up a tutorial that is the natural progression from hello world, its exactly what ive been looking for… apart from one thing…. it doesnt work!lol
Im not sure the exact reason, i have the return statements the import statements, it compiles fine and even runs, however each time i click on the screen i get a force close error…
Heres my code…
package com.kellbot;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
//http://www.kellbot.com/2009/06/android-hello-circle/
public class RoboTown extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
main.addView(new Ball(this,50,50,25));
main.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
FrameLayout flView = (FrameLayout) v;
flView.addView(new Ball(getParent(), x,y,25));
return false;
}
});
}
}
package com.kellbot;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
public class Ball extends View {
private final float x;
private final float y;
private final int r;
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public Ball(Context context, float x, float y, int r) {
super(context);
mPaint.setColor(0xFFFF0000);
this.x = x;
this.y = y;
this.r = r;
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, r, mPaint);
}
}
Id really appreciate the response since this is really the only good tutorial out on the net at the moment!
Thank you
Chachaji
How can i delete one item?
Thanks for this nice tutorial.
Excellent, really good.
Thanks for taking the effort.
Chachaji,
I had a similar problem. Check to make sure your main.xml is set up the same as the example above, I had LinearLayout instead of FrameLayout
Ive finally realised what the problem is, i copied the code perfectly, the reason it hasnt been working is because ive been testing it out on my nexus directly. Once i tried it on the emulator it worked fine.
So my assumption is that theres somthing wrong with the manifest file, maybe i need to add ball.java to it manually. Just need to work on that now.
None the less thank you for the great tutorial!
(p.s. cheers for the response michael)
How can i save everything in one .jpeg?
First of all thanks for such a wonderful article which has been explained in such a simple way. I have tried copying the code. When i run it, i can see a circle on the screen but the moment i click, it force closes. I have frame layout set. Below is the code. Can somebody please help.
RoboTown.java =>
////////////////////////////////////////////////////////////////////////////////////////
package com.kellbot;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
//http://www.kellbot.com/2009/06/android-hello-circle/
public class RoboTown extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
main.addView(new Ball(this,50,50,25));
main.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent e) {
float x = e.getX();
float y = e.getY();
FrameLayout flView = (FrameLayout) v;
flView.addView(new Ball(getParent(), x,y,25));
return false;
}
});
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
Ball.java =>
package com.kellbot;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
public class Ball extends View {
private final float x;
private final float y;
private final int r;
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public Ball(Context context, float x, float y, int r) {
super(context);
mPaint.setColor(0xFFFF0000);
this.x = x;
this.y = y;
this.r = r;
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, r, mPaint);
}
}
////////////////////////////////////////////////////////////////////////////////////////////
main.xml =>
////////////////////////////////////////////////////////////////////////////////////////////
same problem here. It’s my first real tutorial.
I’m using Android 2.2 on the emulator.
I fixed it with this code :
final Activity parent = this;
main.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent e) {
float x = e.getX();
float y = e.getY();
FrameLayout flView = (FrameLayout) v;
flView.addView(new Ball(parent, x,y,25));
return false;
}
});
I would like to know why I have to do that ?
i’m still new in android..
here is a question..
I’m planing to do something like paint using the above code..
can someone teach me which part should i change?
thanks
Hi,
I got this working fine in the emulator but gives the application has stopped unexpectedly. please try again when I touch the screen on a real phone.
then i click on Force Close
My code is as follows:
main.xml
juggler.java
package com.juggler;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import com.juggler.Ball;
public class Juggler extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
main.addView(new Ball(this,50,50,25));
main.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent e) {
float x = e.getX();
float y = e.getY();
FrameLayout flView = (FrameLayout) v;
flView.addView(new Ball(getParent(), x,y,25));
return true;
}
});
}
}
Ball.java
package com.juggler;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
public class Ball extends View {
private final float x;
private final float y;
private final int r;
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public Ball(Context context, float x, float y, int r) {
super(context);
mPaint.setColor(0xFFFF0000);
this.x = x;
this.y = y;
this.r = r;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, r, mPaint);
}
}
Why doesn’t it work on a real phone?
Hi
This is a great tutorial!
exactly what’s missing from the Android tutorial IMO!!!
BUT, when I tried to run as is, it didn’t work. The following code finally worked for me:
I hope this helps someone
=============== HelloCircle.java ============================
package com.example.HelloCircle;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
public class HelloCircle extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
main.addView(new Ball(this,50,50,25));
final Activity parent = this;
main.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent e) {
float x = e.getX();
float y = e.getY();
FrameLayout flView = (FrameLayout) v;
flView.addView(new Ball(parent, x,y,25));
return false;
}
});
}
}
============== Ball.java ============================
package com.example.HelloCircle;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
public class Ball extends View {
private final float x;
private final float y;
private final int r;
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public Ball(Context context, float x, float y, int r) {
super(context);
mPaint.setColor(0xFFFF0000);
this.x = x;
this.y = y;
this.r = r;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, r, mPaint);
}
}
====================================================
Thanks Uri, this code finally works for me
hi guys.
I get process stooped unexpectedly warning when i touch the screen with mouse…
pl tell me y
I just want to say this guide is great. It was exactly what I was looking for. The only problem I had was with “getParent()”. For some reason it does not always work, but I find replacing it with “this” will make it work.
the getparent doesn’t work properly here as it returns a ViewParent or Null. It doesn’t return a Context.
What you actually want is to draw the balls onto the main view context. The getContext worked well for me:
flView.addView(new Ball(findViewById(R.id.main_view).getContext(), x, y, 25));
Thanks for this great tutorial. It’s helping me understand objects and Android a lot better.
Special thanks to @brrt for helping with the line getContext() because until I put that in I got an error.
nice guide !
btw,
how about if I want to do this :
-when I touch and hold down the screen, it shows a circle.
-when I release, it clears the circle
@___@
already done..
just remove the view..
Hello.
I appretiate this manual, it’s great. But 1 question. In your program is the whole screen clickable. But how can I make a Ball clickable? If I use in Ball’s constructor “setOnTouchListener” than the listenes in FrameLayout stops working. It’s all so weird.. 🙁
Is it possible to add onTouch event to the Ball class? So that if I click the screen a new ball will appear. If I touch a particular ball, it will disappear.