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

时间:2014-03-31 20:41:44

标签: java android multithreading progress-bar wait

我的进度条最初设置为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);}

2 个答案:

答案 0 :(得分:5)

嗯,你通过这样做来冻结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();
}

答案 1 :(得分:0)

你可以尝试创建一个runnable并在runOnUiThread(new Runnable());的uithread上运行它吗?

然后执行相同的Thread.sleep(5000);

http://developer.android.com/reference/android/app/Activity.html