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

Fir*_*ges 1 java multithreading android wait progress-bar

我的进度条最初设置为INVISIBLE.单击按钮后,我希望条形显示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);}
Run Code Online (Sandbox Code Playgroud)

Cru*_*ceo 5

那么你就是通过这样做来冻结UI线程,所以一种方法是创建一个新的Thread,并使用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();
Run Code Online (Sandbox Code Playgroud)

并且,正如Chris在下面建议的那样,当Activity关闭时,你应该从Handler中删除任何待处理的消息,以避免在尝试运行不再存在的Activity中的已发布消息/ Runnable时遇到IllegalStateException:

@Override
public void onDestroy() {
    handler.removeCallbacksAndMessages(null);
    super.onDestroy();
}
Run Code Online (Sandbox Code Playgroud)