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

匆匆过客 提交于 2019-12-22 00:13:22

问题


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);
}

回答1:


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



来源:https://stackoverflow.com/questions/15182505/android-postdelayed-works-but-cant-put-it-in-a-loop

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