android 处理程序removeCallbacks 不起作用

问题描述 投票:0回答:4

我正在使用可运行的方式旋转图像。我想旋转图像,例如第四次,然后暂停/停止旋转。我写了一些函数

public void rotateImage(final View myView, final int size) {

    runnable = new Runnable() {

        @Override
        public void run() {

            count++;
            myView.setRotation(myView.getRotation() + size);
            if (count ==3) {
                myHandler.removeCallbacks(runnable);
            }

            myHandler.postDelayed(this, 100);
            // 1000 means 1 second duration
        }
    };
    myHandler.postDelayed(runnable, 100); 

}

我可以旋转图像,但我无法停止/暂停旋转。removeCallbacks 目前不起作用 我的代码有什么问题如果有人知道解决方案请帮助我

android runnable android-handler
4个回答
19
投票

我的 Handler/Runnable 上有相同的逻辑。而且还没有停止。

我所做的是:在我的 Activity 的 OnDestroy 中,我调用了

myHandler.removeCallbacksAndMessages(null);

终于停了。

希望有帮助。


3
投票
/**
 * <p>Removes the specified Runnable from the message queue.</p>
 *
 * @param action The Runnable to remove from the message handling queue
 *
 * @return true if this view could ask the Handler to remove the Runnable,
 *         false otherwise. When the returned value is true, the Runnable
 *         may or may not have been actually removed from the message queue
 *         (for instance, if the Runnable was not in the queue already.)
 *
 * @see #post
 * @see #postDelayed
 * @see #postOnAnimation
 * @see #postOnAnimationDelayed
 */
public boolean removeCallbacks(Runnable action)

removeCallbacks() 仅当可运行对象在消息队列中挂起时才起作用。 您要删除的可运行程序显然正在运行。

你最好自己阻止它。喜欢:

public void rotateImage(final View myView, final int size) {

runnable = new Runnable() {

    @Override
    public void run() {

        count++;
        myView.setRotation(myView.getRotation() + size);
        if (count ==3) {
            //myHandler.removeCallbacks(runnable);
        } else {
            myHandler.postDelayed(this, 100);
        }
        // 1000 means 1 second duration
    }
};
myHandler.postDelayed(runnable, 100); 

}


0
投票

您必须将 Runnable 的创建从函数“rotateImage”内部移至任何函数调用外部。 removeCallbacks 工作正常,但您的 Runnable 对象正在重新创建,尽管它具有相同的内容,但 Id 不同。 这会起作用:

private Runnable runnable = new Runnable() {

        @Override
        public void run() {

            count++;
            myView.setRotation(myView.getRotation() + size);
            if (count ==3) {
                myHandler.removeCallbacks(runnable);
            }

            myHandler.postDelayed(this, 100);
            // 1000 means 1 second duration
        }
    };
public void rotateImage(final View myView, final int size) {

    myHandler.postDelayed(runnable, 100); 

}

0
投票

删除回调时,将令牌传递为 null,它在这里起作用。

myHandler.removeCallbacks(runnable, null)
© www.soinside.com 2019 - 2024. All rights reserved.