简体   繁体   English

进度条完成后执行某些操作

[英]do something when progress bar is completed

I want to toast (or show a dialog) when progressbar ends. 当进度条结束时,我想要吐司(或显示对话框)。 I tried to do this with if in run() method, but it causes the following error: 我试图做到这一点if在run()方法,但它会导致以下错误:

Can't create handler inside thread that has not called Looper.prepare()

how can I do that? 我怎样才能做到这一点?

This is my code: 这是我的代码:

@Override
public void run() {
    int myProgress = 0, Speed = 50;
    ProgressBar myProgressBar = (ProgressBar) findViewById(R.id.progressbar);

    while (myProgress<750){
        try{
            Thread.sleep(Speed);
            myProgress++;
            if (myProgressBar != null) {
                myProgressBar.setProgress(myProgress);
            }
        }
        catch(Throwable t){ }
    }
}
   runOnUiThread(new Runnable() {
      public void run() {
          //your code here 
      }
   });

Change like this. 像这样改变。

runOnUiThread(new Runnable() {
  public void run() {
    int myProgress = 0, Speed = 50;
    ProgressBar myProgressBar = (ProgressBar) findViewById(R.id.progressbar);

    while (myProgress<750){
    try{
        Thread.sleep(Speed);
        myProgress++;
        if (myProgressBar != null) {
            myProgressBar.setProgress(myProgress);
        }
    }
    catch(Throwable t){ }
}      
}
});

Worker threads are meant for doing background tasks and you can't show anything on UI within a worker thread unless you call method like runOnUiThread. 工作线程用于执行后台任务,除非您调用runOnUiThread之类的方法,否则无法在工作线程中的UI上显示任何内容。 If you try to show anything on UI thread without calling runOnUiThread, there will be a java.lang.RuntimeException. 如果您尝试在不调用runOnUiThread的UI线程上显示任何内容,则会出现java.lang.RuntimeException。 Tell me if you still face any problem. 告诉我你是否还有任何问题。

I tried this and it works now: 我试过这个,它现在有效:

public void run() {
    int myProgress = 0, Speed = 50;
    ProgressBar myProgressBar = (ProgressBar) findViewById(R.id.progressbar);
    while (myProgress<750){
        try{
            Thread.sleep(Speed);
            myProgress++;
            if (myProgressBar != null) {
                myProgressBar.setProgress(myProgress);
            }
        }
        catch(Throwable t){ }
}

final int finalMyProgress = myProgress;

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (finalMyProgress == 750)
                Toast.makeText(word_guess2.this, "hi", Toast.LENGTH_SHORT).show();
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM