【问题标题】:wait 5 seconds to a progress bar be invisible in android等待 5 秒以使进度条在 android 中不可见
【发布时间】:2014-03-31 20:41:43
【问题描述】:

我最初设置了一个不可见的进度条。单击按钮后,我希望进度条出现 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);}

【问题讨论】:

    标签: java android multithreading progress-bar wait


    【解决方案1】:

    你这样做是在冻结 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();
    }
    

    【讨论】:

    • 确保检查是否从活动 onStop 中的处理程序中删除了回调
    • 另外,你为什么不调用 handler.postDelayed(new Runnable())。创建单独的线程会增加很多开销和更多需要管理的东西。
    • 我在考虑使用 postDelayed,但它并没有真正解释线程和他遇到的 UI 阻塞。当然,我可以向他扔简短的 sn-p,但从长远来看,这无济于事。至于删除回调,是的,你应该,我正在为你更新帖子~
    • 是的,但是您确实使用他的示例提供了一些代码,但不建议删除线程,因为处理程序不再需要它。然后他就可以弄清楚其余的了。
    • 你不需要休眠当前线程,使用处理程序时也不需要线程。通过在您的示例中使用单独的线程,您可以为 OP 遇到更多问题打开大门。我并不是说代码 sn-ps 需要准确或 100% 完整,但不要让这个人走上错误的道路。
    【解决方案2】:

    您可以尝试使用runOnUiThread(new Runnable()); 创建一个runnable 并在uithread 上运行它?

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 2016-05-05
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多