Question

Sorry I am a noob I've read countless tutorials about making a simple timer and was wondering why it doesn't work until I noticed it is the while-loop causing the issue o.O I have removed it and then it works but only 1 time I need to use the loop though so the movement finishes :C

Heres the code:

old_x is the coordinate from an ImageView and new_x from the onTouch Event, maybe the problem because I am casting them as an int? I don't know what I need to do so it works please help O:

    while(old_x != new_x)
    {
        timedMoveIV(100);
        old_x = (int)img.getX();
    }

It calls this method which works if I do it without the loop.

public void timedMoveIV(int time_ms)
{
    //sleep for time_ms milliseconds
    Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
         public void run() { 
            if(new_x > img.getX())
            {
            img.setX(img.getX() + 1);
            }
            else
            {
            img.setX(img.getX() - 1);   
            }
         } 
    }, time_ms);
}
Was it helpful?

Solution

Your main problem is that your loop doesn't take a break, so it's constantly running the function, posting a gazillion runnables.

What you want to do is make the runnable call itself after another 100 ms. Take a look at this example:

if(old_x != new_x)
    timedMoveIV(100);

Here you simply call the function once. After that, you let the posted runnable decide whether or not it needs to move again:

public void timedMoveIV(final int time_ms)
{
    Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
        public void run() 
        { 
            if(new_x > img.getX())
                img.setX(img.getX() + 1);
            else
                img.setX(img.getX() - 1); 

            // if not in position, call again
            if((int)img.getX() != new_x)
                timedMoveIV(time_ms); 
        } 
    }, time_ms);
}

It should stop once img.getX() == new_x. Notice the cast to int, though, because if you leave it out, you might get some oscillation as it gets within a pixel of the destination.

This assumes that new_x is an int. If it's a float as well, you should either cast both to int to compare, or compare them to a minimum threshold. For instance, if there's less than 0.5 difference, treat it as "done".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top