user220201
user220201

Reputation: 4534

Android graphics draw on a canvas question

I am writing my first android app. So am still in the learning phase.

Its very simple, I draw a graphic in the onDraw() in the center of the screen and with the onTouch event will have to move the graphic to the point where the user touched. For this the onTouch event will start a thread and update the graphic. The problem is the canvas.draw() is working when called from onDraw() but does not update the canvas/screen when called from within the thread.

My function drawSplash( Canvas c, Location l );

I call the same function in both the onDraw() and the thread.

The only difference in the code I can see is I am storing the Canvas object passed in to me in the onDraw() function in a variable in my class so that I can use it in the thread again. This somehow feels wrong. If so, what is the correct way to do this? Can I get the Canvas object anytime I want? How do I do that?

Upvotes: 0

Views: 2870

Answers (3)

Phil
Phil

Reputation: 49

In my understanding you could set the baseboard as a background image.

If you do that you do not have to constantly redraw it but I am not 100% sure of that.

Have a look at the Lunar Lander code on the Android Dev sight here:

http://developer.android.com/resources/samples/LunarLander/index.html

Phil

Upvotes: 0

Iulius Curt
Iulius Curt

Reputation: 5104

Here is a slightly different approach.

Make some global fields like this:

    private int mX;  
    private int mY;

And then, in your onTouch() method (you use the onTouch of the same View class, right?) you change those fields and then call the invalidate() method:

    public boolean onTouch (View v, MotionEvent event) {
        mX = event.getX();
        mY = event.getY();
        invalidate();
    }

So now, the onDraw() method will simply draw your splash to the position (mX, mY).

Upvotes: 1

Marcos Vasconcelos
Marcos Vasconcelos

Reputation: 18276

You have to .invalidate() your view with has the onDraw method overrited. Each time it's called it should draw the Graphics on the right position.

And you should call the .invalidate() method inside the Main Thread.

Upvotes: 1

Related Questions