Android postDelayed works but can't put it in a loop?

情到浓时终转凉″ 提交于 2019-12-04 18:17:55

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".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!