我有一个最初设置为不可见的进度条。单击按钮后,我希望进度条显示 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/