Skip to content.

June 26, 2009 | Programming

Android: Hello Circle

Note: This article is pretty long in the tooth, and refers to a version of Android that is at least two versions old, and likely many more. I haven’t gone back to update things to see what works and what doesn’t. A few people have posted solutions in the comments so if you’re running into issues try skimming those first.

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

Related Posts

There are no related posts on this entry.

Comments

  1. danielbln says: June 28, 2009

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

  2. danielbln says: June 30, 2009

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

  3. Dave says: July 1, 2009

    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!

    • ipis says: June 29, 2011

      Try to add

      import android.view.MotionEvent;
      import android.widget.FrameLayout;

    • sunny says: September 29, 2011

      Thanx a lot , I was getting those errors

  4. Richard says: August 4, 2009

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

  5. kiks says: August 5, 2009

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

  6. Lindsey says: August 23, 2009

    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!

  7. p47 says: September 1, 2009

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

  8. p47 says: September 1, 2009

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

  9. emeric says: September 17, 2009

    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

  10. emeric says: September 17, 2009

    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

    • Jim says: June 28, 2011

      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.

      • Jim says: June 30, 2011

        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.

  11. RDRush says: October 22, 2009

    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.

  12. Mila says: October 24, 2009

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

    Thanks.

    • Kellbot says: October 24, 2009

      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!

  13. Jayz says: October 31, 2009

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

    • adrock2999 says: September 25, 2010

      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

    • CJDS says: November 20, 2010

      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

    • Adam says: April 14, 2011

      Thank you soooooo much!

    • Neil says: May 26, 2011

      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

  14. m says: November 2, 2009

    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!

  15. Matt says: November 4, 2009

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

    • Kellbot says: November 4, 2009

      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.

      • Matt says: November 5, 2009

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

  16. Sasikumar says: December 4, 2009

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

  17. condorhero says: December 5, 2009

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

  18. cykan says: December 9, 2009

    Thank you very much! You were a great help!

    Greetz!

  19. Roboturner says: December 29, 2009

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

  20. rishi says: January 6, 2010

    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?

  21. rishi says: January 7, 2010

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

  22. MaoMao says: March 7, 2010

    Great Tutorial, Thanks a lot !

  23. Stan says: March 18, 2010

    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?

  24. cpul says: March 29, 2010

    Thanks a lot !

    How do you fill this circle with an image ?

  25. kyle says: April 6, 2010

    very good – thanks – gonna do any more android tutorials?

  26. Tony says: April 7, 2010

    Thanks a lot! :)

  27. Jed says: April 14, 2010

    This tutorial ROCKS!!! Please provide more tutorials : )

  28. Anand says: May 4, 2010

    Great Tut!.. simple and clear, thanks a lot :)

  29. Andy says: May 19, 2010

    Cracking tutorial, i’ve been looking for a good FrameLayout tutorial for a while, this one is excellant.

    cheers :)

  30. Chris says: June 12, 2010

    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…

  31. Sudha says: June 16, 2010

    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.

  32. Jill says: June 27, 2010

    this is so helpful thank you thank you thank you thank you thank you!!

  33. coreation says: June 28, 2010

    hmmm getParent() is indeed a strange thingy , tell me if you don’t understand it , how did you come up with it ?

  34. Chachaji says: July 4, 2010

    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

  35. pemko says: July 5, 2010

    How can i delete one item?

  36. Ravindra kumar says: July 6, 2010

    Thanks for this nice tutorial.

  37. Andrew says: July 6, 2010

    Excellent, really good.

    Thanks for taking the effort.

  38. Michael says: July 10, 2010

    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

    • Chachaji says: July 15, 2010

      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)

  39. pemko says: August 19, 2010

    How can i save everything in one .jpeg?

  40. Prinks says: August 20, 2010

    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 =>

    ////////////////////////////////////////////////////////////////////////////////////////////

  41. Sebastien says: August 22, 2010

    same problem here. It’s my first real tutorial.

    I’m using Android 2.2 on the emulator.

    • Sebastien says: August 22, 2010

      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 ?

  42. Noobie says: September 13, 2010

    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

  43. Derrick says: October 15, 2010

    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?

  44. Uri says: October 31, 2010

    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);
    }
    }
    ====================================================

    • Jd says: August 8, 2011

      Thanks Uri, this code finally works for me

  45. Aditya says: November 23, 2010

    hi guys.

    I get process stooped unexpectedly warning when i touch the screen with mouse…

    pl tell me y

  46. Mike says: November 26, 2010

    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.

  47. brrt says: December 23, 2010

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

  48. Eugene van der Merwe says: December 30, 2010

    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.

  49. boyboyjc says: January 4, 2011

    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

    @___@

    • boyboyjc says: January 4, 2011

      already done..
      just remove the view..

  50. Racky says: January 18, 2011

    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.

Add a Comment