4

我有一系列 postDelayed 处理程序。当用户在我想要的任何时候点击停止按钮时,我无法设置一个停止处理程序的数学。

我将不胜感激有人能够提供的任何帮助。谢谢

while (!lessonIsRunning) {
        Handler handler0 = new Handler();
        handler0.postDelayed(new Runnable() {
          @Override
          public void run() {
              plate1.setVisibility(ImageView.VISIBLE);
              plate2.setVisibility(ImageView.VISIBLE);
              plate3.setVisibility(ImageView.VISIBLE);
          }
        }, 6000);

        Handler handler1 = new Handler();
        handler1.postDelayed(new Runnable() {
          @Override
          public void run() {
              apples1.setVisibility(ImageView.VISIBLE);
          }
        }, 9000);

        Handler handler2 = new Handler();
        handler2.postDelayed(new Runnable() {
          @Override
          public void run() {
              plus1.setVisibility(TextView.VISIBLE);
          }
        }, 9250);
}
public void stopLesson(View V){

}
4

2 回答 2

12

而不是以匿名方式编写 Runnable 任务,您必须使用名称定义它,以便稍后您将有一个指向它的链接以删除:

//there is no need for multiple handlers 
//handler must be declared outside all functions, in order for you to use it everywhere. 

Handler handler = new Handler(); 
Runnable myFirstTask  = new Runnable (){
         @Override
              public void run() {
                  plate1.setVisibility(ImageView.VISIBLE);
                  plate2.setVisibility(ImageView.VISIBLE);
                  plate3.setVisibility(ImageView.VISIBLE);
              } };

    Runnable mySecondTask = new Runnable(){
        @Override
              public void run() {
                  plus1.setVisibility(TextView.VISIBLE);
              }

    };

    Runnable myThirdTask = new Runnable(){
        @Override
              public void run() {
                  apples1.setVisibility(ImageView.VISIBLE);
              } }

    //you can put different tasks on the same handler object

    while (!lessonIsRunning) {   
            handler.postDelayed(myFirstTask,6000);   
            handler.postDelayed(mySecondTask,9250);   
            handler.postDelayed(myThirdTask,9000); 
} 
public void stopLesson(View V){ 
    //notice that you don't need these, because the handlers are not recursive 
    //you don't have lines "handler.postDelayed(sameTask,someTime);" 
    //in your run Method of the runnable
 if(handler!=null){
    handler.removeCallbacks(myFirstTask);
    handler.removeCallbacks(mySecondTask); 
    handler.removeCallbacks(myThirdTask); 
    //if this method is inside onPause or onDestroy add this line as well: 
    handler=null; 

}
 }
于 2013-03-05T17:23:59.020 回答
4

你可以给

handler0.removeCallbacksAndMessages(null);
handler1.removeCallbacksAndMessages(null);
handler2.removeCallbacksAndMessages(null);

试一试。该文档说,当您提交空令牌时,所有回调和消息都将被删除。

于 2013-03-05T16:28:59.320 回答