java - 等待 5 秒到进度条在 android 中不可见

标签 java android multithreading progress-bar wait

我有一个最初设置为不可见的进度条。单击按钮后,我希望进度条显示 5 秒而不是消失。我正在使用 Thread.sleep(5000) 但没有任何反应

public void dec(View v) throws InterruptedException{
ProgressBar pbar = (ProgressBar) findViewById(R.id.bar);
pbar.setVisibility(View.VISIBLE);
Thread.sleep(5000);
pbar.setVisibility(View.INVISIBLE);}

最佳答案

这样做会卡住 UI 线程,因此一种方法是创建一个新线程,并使用 Handler 回发到 UI 线程,这样它就不会被阻塞并可以继续绘图。

例如:

final ProgressBar pbar = (ProgressBar) findViewById(R.id.bar); // Final so we can access it from the other thread
pbar.setVisibility(View.VISIBLE);

// Create a Handler instance on the main thread
Handler handler = new Handler();

// Create and start a new Thread
new Thread(new Runnable() { 
    public void run() {
         try{
             Thread.sleep(5000);
         }
         catch (Exception e) { } // Just catch the InterruptedException

         // Now we use the Handler to post back to the main thread
         handler.post(new Runnable() { 
            public void run() {
               // Set the View's visibility back on the main UI Thread 
               pbar.setVisibility(View.INVISIBLE);
            }
        });
    }
}).start();

而且,正如 Chris 在下面建议的那样,您应该在 Activity 关闭时从 Handler 中删除所有未决消息,以避免在尝试在不再存在的 Activity 中运行发布的消息/Runnable 时遇到 IllegalStateException:

@Override
public void onDestroy() {
    handler.removeCallbacksAndMessages(null);
    super.onDestroy();
}

关于java - 等待 5 秒到进度条在 android 中不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22771756/

相关文章:

java - 在 Android 中使用 FFT

java - 使用 AtomicReference 对多个预期值进行比较和设置

linux - 良好的 POSIX 线程编程视频培训

java - 需要解释 OpenCV Android 行为

java - 关于java父类(super class)和子类的初学者问题

java - JSP 无法正确评估数组索引

android - 根据类别对项目列表进行排序 (Android)

android - 在带有 GeoServer 的 Android 应用程序中使用 getTileURL

c# - 如何从 .Net 中的超线程中获得最大 yield

java - 签名 jar 的作者未知