Android: Hello Circle

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):

1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:id="@+id/main_view"
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="#FF66FF33" />

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:

1
2
3
4
5
6
7
8
9
10
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:

1
2
3
4
5
6
7
8
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):

6
7
8
9
10
11
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:

9
10
11
12
13
14
15
16
17
18
19
    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:

12
13
14
15
16
17
18
19
20
21
22
23
24
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():

9
10
11
  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:

11
12
    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:

12
13
14
15
16
17
18
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.

12
13
14
15
16
17
18
19
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:

12
13
14
15
16
17
18
19
20
21
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).

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • RSS
  • StumbleUpon
  • Twitter

Tags: , , , , ,

  1. Thank you. Working my way up is exactly what I like to do and so your tutorial is greatly appreciated. :)

    Reply

  2. Oh, and another tutorial would of course be super fantastic. :)

    Reply

  3. 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!

    Reply

  4. thanks very much! This is the first good tutorial which I find :)

    Reply

  5. Excellent tutorial ! Nice style of writing ! keep it up !

    Reply

  6. 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!

    Reply

  7. @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!

    Reply

  8. Why you don’t have return statement in onTouch method? its boolean.

    Reply

  9. 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

    Reply

  10. 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

    Reply

  11. 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.

    Reply

  12. How about clicking the screen, rather than touching?
    Is is still the onTouch method?

    Thanks.

    Reply

    1. 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!

      Reply

  13. 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 :)

    Reply

  14. 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!

    Reply

  15. 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 :)

    Reply

    1. 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.

      Reply

      1. Thanks, it worked :D Now I’m gonna figure out how to get it to constantly draw, like a paint program.

        Reply

  16. Very Nice!… Develop more application like this!…………….

    Reply

  17. I think you forgot to “return true;” in function onTouch.

    Reply

  18. Thank you very much! You were a great help!

    Greetz!

    Reply

  19. 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? :(

    Reply

  20. 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?

    Reply

  21. nevermind.. i found the error! lol
    i forgot to instantiate the Paint class.. tadaaaaaaa!!!

    Reply

  22. Great Tutorial, Thanks a lot !

    Reply