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.
I think that you cant use onDraw in class extending an Activity because of using Canvas, you need to create a Custom component extending some View and there handle you action,and what do you need to do that=>
1.Extend an existing View class or subclass with your own class.
2.Override some of the methods from the superclass. The superclass methods to override start with ‘on’, for example,onDraw(), onMeasure(), onKeyDown(). This is similar to the‘on’ events in Activity that you override for lifecycle and other functionality hooks.
3.Use your new extension class. Once completed, your new extension class can be used in place of the view upon which it was based.
You don't need to use
View.onDraw()
for this purpose. Just use layouts and place any drawable image next to your counter, let's say a textview, using thedrawableLeft
attribute.txtview_counter.drawableLeft="@drawable/xxx"
Simple example using onDraw function-it requires class to extend view
Context to get the current activity context
Couldn't you just place an ImageView next to your counter? You could do that in your xml layout file:
Or in your acrivity:
If you want to use a custom view and override the onDraw() method here's what you need to do:
For any doubt, you can refer to Android Training