停止Runnable

时间:2016-02-21 12:52:54

标签: java android handler runnable

在我之前的问题Make button method if button clicked or not cliked中,我找到了这样的答案:

Handler visibilityToggler;
Runnable visivilityRunnable;


  visibilityToggler = new Handler();

        visivilityRunnable = new Runnable() {
            @Override
            public void run() {

                 // isUserClickedButton is used to keep record if user has pressed button within 1 sec
                //  keep isUserClickedButton = true for first time as it will run 
                if (!isUserClickedButton) {

                    // user not pressed button
                    Toast.makeText(context,"You are not pressed the Button",Toast.LENGHT_LONG).show();
                }

                // toggle visibility
                Random generator = new Random();
                number = generator.nextInt(16);

                for (int i = 0; i < buttons.length; i++) {
                    if (i == number)
                        buttons[i].setVisibility(View.VISIBLE);
                    else
                        buttons[i].setVisibility(View.INVISIBLE);
                }

            // again start the visibility 
              visibilityToggler.postDelayed(visivilityRunnable,1000);

                // make it false as visibility is toggled and we want to track button pressed from start
                isUserClickedButton = false;


            }
        };

visibilityToggler.postDelayed(visivilityRunnable,1000);

现在我的问题是:如何阻止Runnable?
任何人都可以提供代码示例吗?

更新:

我在按钮上使用了removecallbacks()

          public void onClick(View v){
             visibilityToggler.removeCallbacks(visivilityRunnable);
             }        

但是可以停止运行,任何人都可以提供帮助吗?

1 个答案:

答案 0 :(得分:0)

在处理程序外定义runnable。然后调用handler.removeCallbacks(visivilityRunnable);,以便停止处理程序。