In R&D for a related view I’m attempting to build, I started a simple project to grasp how to do more of the basic drawing “stuff” before getting ahead of myself.
Like my other question states, there’s a lot of information out for SurfaceView threading and animation, but I feel for this application, that may be overkill. I’ll be showing somewhere between 10 and perhaps hundreds of the final View on screen at once, and from what I gather about SurfaceView it’s usually used as the main view of an Activity (game screen, etc).
This R&D app draws a few circles, and calculates the distance between the target (red lines) and the previous position (white lines):

My onDraw is pretty straightforward, but I’m having quite a hard time figuring out how to implement a Thread or Handler, or any sort of non-UI loop to calculate the values between the target and the main circle.
I have a private static inner Thread that I thought would be easy, but no dice. The latest Frankencode:
private static class DragThread extends Thread {
private DragTest view;
private boolean animate;
private float currentY, targetY, delta, inc;
public DragThread(View v){
view = (DragTest)v;
targetY = view.mTargetData.getY();
currentY = view.mMainData.getY();
}
public void run(){
while(Math.abs(currentY - targetY) >= 0){
view.mMainData.setY(currentY + 10f);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}finally{
view.postInvalidate();
}
}
Log.e(TAG, "Loop finished");
}
}
mMainData and mTargetData are just POJOs holding the positional values of each circle, which my onDraw uses to update the position:
mMainData = new CircleData(startXposition, startYposition, radius);
…and retrieved using standard getters.
Essentially, I know I’ll need to start the loop logic when I lift my finger, but I’ve gotten a few errors ranging from “Thread Already Started”, to freezes and crashes. Handlers give me leak warnings… man. I’m spent.
Here’s the onTouchEvent for my view, with explanation of each event:
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
if(action == MotionEvent.ACTION_DOWN){
// set some flags for drawing, update "hero" circle Y position
// based off event data
}else if(action == MotionEvent.ACTION_UP){
// reset flags that dictate ghost circle drawing, etc. and invalidate
// I think I need to start the loop here, but how?!
// new Thread().start()? Some sort of Handler? GAH!
}else if(action == MotionEvent.ACTION_MOVE){
// update mMainData Y position which is passed into onDraw, invalidate to reflect movement changes
}
return false;
}
Based on this article, the solution was apparently staring me in the face, but I thought it was harder than it really is.
Final solution for the sample application in question is to have the view implement
Runnable, set up a new animationThreadwhen the user lifts their finger, and use aScrollerto compute the offset.