【问题标题】:Android. How to stop a handler once it executed a runnable once安卓。如何在处理程序执行一次可运行时停止处理程序
【发布时间】:2015-03-08 09:53:56
【问题描述】:

编辑:代码现在可以工作了。我最终从 createDialog() 中调用了 loadingIllusionLoader()...

我试图在用户按下按钮后显示“假”进度条。我希望进度条出现一些随机时间〜 2000 毫秒,然后出现一个对话框以及隐藏进度条(因为它“加载”)。

我被告知尝试使用处理程序,因为 Thread.sleep 锁定了 UI,而我真的不想这样做。但是,一旦我执行下面的代码,它就会运行处理程序的 postDelayed 函数,并且每隔一段时间就会出现一个新的对话框......处理程序一遍又一遍地执行自己。如何停止处理程序。处理程序上的 removeCallbacksAndMessages 函数是一个选项,但我不确定如何完全停止打开对话框。

public void loadingIllusionLoader()
{
    ProgressBar theCircleLoader = (ProgressBar) findViewById(R.id.progressBar2);
    theCircleLoader.setVisibility(View.VISIBLE);
    int timeToRest = (int) (Math.random() * 1000) + 1500;

   final Handler newHandle = new Handler();
    newHandle.postDelayed(new Runnable() {
        @Override
        public void run() {
            createDialog();
            hidingIllusionLoader();
            newHandle.removeCallbacksAndMessages(null);

        }
    }, timeToRest);
}

public void hidingIllusionLoader()
{
    ProgressBar theCircleLoader = (ProgressBar) findViewById(R.id.progressBar2);
    theCircleLoader.setVisibility(View.INVISIBLE);
}

【问题讨论】:

    标签: android android-handler


    【解决方案1】:

    我认为您更愿意使用CountDownTimer

    CountDownTimer timer = new CountDownTimer( 10000, 1000 ) { 
      @Override public void onTick( long millisUntilFinished ) {
        theCircleLoader.setProgress( theCircleLoader.getProgress() - 1 );
      }
      @Override public void onFinish() {
        theCircleLoader.setVisibility(View.INVISIBLE);
      }
    };
    

    编辑:几乎忘记了:

    timer.start();
    

    EDIT2:

    看了你的代码后,我建议你修改一下:

        Random rnd = new Random();
        int progressBarMax = rnd.nextInt( 10 ) + 1; // 10 - change it the way you like
        int timeToRest = progressBarMax * 500;
        theBarLoader.setMax( progressBarMax );
        theBarLoader.setProgress( 0 );
    
        CountDownTimer theTimer = new CountDownTimer(timeToRest, 500)
    
        {
            @Override public void onTick( long millisUntilFinished ) {
                 theBarLoader.setProgress( theCircleLoader.getProgress() + 1 );
            }
            @Override public void onFinish() {
                theCircleLoader.setVisibility(View.INVISIBLE);
               // theBarLoader.setVisibility(View.INVISIBLE);
                createDialog();
            }
        };
        theTimer.start();
    

    【讨论】:

    • 我已经实现了 CountDownTimer,并希望水平 ProgressBar 相应地加载。当我 start() 计时器时,进度条在 onTick() 期间没有做任何事情;我将您的 -1 设置为 +10,希望在每个“滴答”上它会增加 10%,但它只会在柱上增加 10% 并停止。
    • -1 我的意思是“倒计时”,因此progressBar 递减。您可以使用 +1 或任何其他正数来增加它,从 0 开始
    • 当我运行你所拥有的东西时,它并没有真正显示任何进展或递减进展。
    • 你使用了什么构造函数参数?你看过 CountDownTimer Javadoc 吗?
    • 我的完整代码在这里:pastebin.com/iupRJpZi。我想我只是使用了没有参数的 new CountDownTimer()
    猜你喜欢
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 2017-10-05
    • 2012-03-23
    • 2012-01-08
    • 1970-01-01
    相关资源
    最近更新 更多