Android: How to use the onDraw method in a class extending Activity?

Turbosheep picture Turbosheep · Jan 19, 2014 · Viewed 30.1k times · Source

As a beginner, I've been building a simple counter application using a simple layout xml and a class called 'Counter', which derives (extends) from the class Activity.

Now, I want to load a bitmap (png file) to place next to the counter. I've been reading up on onDraw(), but it requires the class to extend 'View'. I've been trying to create an object of this class to use this instead, to no avail. I'm a bit stumped about this concept, how to do it easily. If anyone could explain, I'd appreciate it.

Answer

venugopal picture venugopal · Jun 26, 2014

Simple example using onDraw function-it requires class to extend view

Context to get the current activity context

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(new myview(this));


}

class myview extends View
{

    public myview(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }
    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        int x=80;
        int y=80;
        int radius=40;
        Paint paint=new Paint();
        // Use Color.parseColor to define HTML colors
        paint.setColor(Color.parseColor("#CD5C5C"));
        canvas.drawCircle(x, y, radius, paint);
    }

}

}