[英]do something when progress bar is completed
当进度条结束时,我想要吐司(或显示对话框)。 我试图做到这一点if
在run()方法,但它会导致以下错误:
Can't create handler inside thread that has not called Looper.prepare()
我怎样才能做到这一点?
这是我的代码:
@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
}
});
像这样改变。
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){ }
}
}
});
工作线程用于执行后台任务,除非您调用runOnUiThread之类的方法,否则无法在工作线程中的UI上显示任何内容。 如果您尝试在不调用runOnUiThread的UI线程上显示任何内容,则会出现java.lang.RuntimeException。 告诉我你是否还有任何问题。
我试过这个,它现在有效:
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.