当进度条状态达到 100 时,我尝试运行一些代码 fragment 。(在本例中为 diggingStatus) 但由于某种原因 Log.d 代码被调用了 2 次而不是 1 次。我猜我的 if(diggingStatus==100) 条件放错了地方。
new Thread(new Runnable() {
private Handler diggingHandler = new Handler();
@Override
public void run() {
while(diggingStatus < 100){
// Update the progress status
diggingStatus +=1;
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
// Update the progress bar
diggingHandler.post(new Runnable() {
@Override
public void run() {
diggingbar.setProgress(diggingStatus);
if(diggingStatus==100){
//Run this code when progress is completed.
Log.d("i got called","i got called "); //Why this is called 2 times?
}
}
});
}
}
}).start();
最佳答案
由于您处理异步消息,因此当两者都执行时变量 diggingStatus 已经是 100。
您还必须将进度量发送给处理程序,如下所示:
final int progress = diggingStatus; //get only the current
// Update the progress bar
diggingHandler.post(new Runnable() {
@Override
public void run() {
diggingbar.setProgress(progress);
if(progress==100)
Log.d("i got called","i got called ");
}
});
关于java - 为什么代码被调用2次? Java Android 线程处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48873567/