我想在进度条结束时干杯(或显示对话框)。我尝试在run()方法中使用if
执行此操作,但它会导致以下错误:
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){ }
}
}
答案 0 :(得分:0)
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。 告诉我你是否还有任何问题。
答案 1 :(得分:0)
我尝试了这个,它现在有效:
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();
}
});
}