Simon Forsberg Simon Forsberg - 2 months ago 13
Android Question

Moving Android View and preventing onDraw to be called over and over again

I'm extending the

View
-class, to what I call
MyView
. (I've added some properties which basically says what is drawn on the object, and handling this)

I'm moving an object of this class once every few milliseconds, this works great. I'm using
this.layout(left, top, right, bottom);
to move the MyView. But it seems like every time the view is moved, it is redrawn (onDraw is called). Is this necessary? The contents of
MyView
does not change when it is moved. In fact, the contents will never change - it's created in one way, moves around, and later gets destroyed.

I'm using
onDraw
because every time it is created I want it to draw some text or some numbers on it. I used to extend
ImageView
and use
setImageResource
but I realized I want more than just different images on this and creating images for all kinds of text and number content this object can have did not feel right.

It is also important that my object can receive onTouch events, which works fine today.

My onDraw-method contains at the moment: (this will change, when I get it to not repaint all the time)

@Override
public void onDraw(Canvas canvas) {
Paint p = new Paint();
p.setARGB(255, 0, 255, 255);
canvas.drawRect(0, 0, 32, 32, p);
}


So the question is: Can I have an object that is drawn dynamically when created, have the possibility to receive touch events (I could solve this another way so it's not very important), and move it around without it being repainted (most important)?

The reason is: I'm going to have several objects (could be 100+) of this class and I believe that the application will be slowed down by repainting the objects all the time.

Edit:
If it's not possible with a View, is there any alternative that I can use?

Answer

But it seems like every time the view is moved, it is redrawn (onDraw is called). Is this necessary?

Yes.

A View object will ALWAYS call onDraw whenever its moved since invalidate method must be called so the text or whatever you are drawing in that object will be painted in the new position.

Can I have an object that is drawn dynamically when created, have the possibility to receive touch events

Yes, depending on what you want to achieve, you can override the method onTouchEvent on your class that extends View or implement a TouchListener to your object

Note: It is not advisable to draw that much view objects (100+) I remember some Google guys mentioning this, I'll edit this with the link as soon as I find it.

Comments