【问题标题】:Progressbar in Android Studio is not showing while delayAndroid Studio 中的进度条在延迟时不显示
【发布时间】:2022-01-12 13:03:18
【问题描述】:

我有一个方法,我希望延迟一秒,在延迟运行时应该有一个加载动画 (ProgressBar)。

现在,当方法正在运行时,加载动画没有出现。如果我不调用Timeout,它确实会出现,并且当我之后不使其不可见时,它会在超时后出现。

如何在超时运行时显示加载动画?我在尝试使用 Thread.sleep(1000) 时遇到了类似的问题。

public void firstMethod(){
    ProgressBar pgLoading = (ProgressBar) findViewById(R.id.pgLoading);
    
    pgLoading.setVisibility(VISIBLE);
    
    try {
        TimeUnit.SECONDS.sleep(1);
    }catch(InterruptionException ex){
        ex.printStackTrace();
    }

    pgLoading.setVisibility(INVISIBLE);
}

【问题讨论】:

    标签: java android android-studio


    【解决方案1】:

    通过调用 sleep 方法,您可以让 UI 线程在此期间休眠 1 秒钟,UI 线程上不会发生任何事情,因此您看不到 ProgressBar。您应该改为使用TimerTask 等待这一秒,然后关闭 ProgressBar。 查看此link,了解如何使用 TimerTask。

    【讨论】:

      【解决方案2】:

      主线程不能被阻塞。这将导致整个渲染停止。这就是为什么您只能在超时后才能看到结果。

      这类操作应该在其他线程中处理。如果您使用 Java,则可以使用 Runnables,但您应该考虑迁移到 Kotlin 以使用协程。

      例如:

          pgLoading.setVisibility(VISIBLE);
          new Thread() {
              public void run() {
                  Thread.sleep(1000);
                  runOnUiThread(new Runnable() {
                     @Override
                     public void run() {
                        pgLoading.setVisibility(INVISIBLE);
                     }
                  });
                 }
                }
              }.start();
      

      【讨论】:

        【解决方案3】:

        发生这种情况是因为当前线程正在暂停。为避免这种情况,请将您的延迟/长时间进程置于不同的线程中。例如:

        public void firstMethod(){
                    ProgressBar pgLoading = (ProgressBar) findViewById(R.id.pgLoading);
        
                    pgLoading.setVisibility(View.VISIBLE);
        new Thread(()->{
        //    Do all your long process here
            try {
                TimeUnit.SECONDS.sleep(1);
            }catch( InterruptedException ex){
                ex.printStackTrace();
            }
            runOnUiThread(() -> pgLoading.setVisibility(View.INVISIBLE));
        
        }).start();
        
        
        
        
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多