我将以下线程形式称为 MainActivity
通过调用方法 StartQuery().start();
但我有一个神秘的问题(对我来说是神秘的:())。 Thread
在这种方法中:
private Thread startQuery(){
return new Thread(() -> {
for(int i = 1; i <= NUMBER_OF_QUERY && isThreadAlive; i++){
int tempTime = timePerQuery;
txtUserResultInput.setText("");
TextView tv = findViewById(R.id.txtCorrectness);
tv.setText("");
int finalI = i;
runOnUiThread(() -> {
Random random = new Random();
int num1 = Math.abs(random.nextInt(maxNumb1)), num2 = Math.abs(random.nextInt(maxNumb2));
Log.i("test", num1 + " - " + num2);
String strNum1 = num1 + "", strNum2 = num2 + "";
txtOp.setText(typeOfOperation);
equalizeNumbers(strNum1, strNum2, num1, num2);
queryCount = finalI;
String count = "Query No: " + queryCount;
txtQueryCount.setText(count);
});
while (tempTime > 0 && isThreadAlive){
int sec = tempTime/1000,
min = sec/60;
int sec1 = sec%60;
String s = min + " : " + sec1;
txtRemainingTime.setText(s);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
tempTime -= 1000;
}
}
isThreadAlive = false;
});
}
我说神秘是因为:
我曾经 View.setText();
内外兼修 runOnUiThread();
.
但是 tv.setText();
以及 txtRemainingTime.setText(s);
工作很好,虽然这是外面的 runOnUiThread();
.
同时也会产生误差 Only the original thread that created a view hierarchy can touch its views
当我不使用 runOnUiThread();
那部分代码。这里有错误 txtOp.setText(typeOfOperation);
以及 txtQueryCount.setText(count);
.
最后,如果我将下面的代码放在while循环中,该循环运行良好(即使在 txtRemainingTime.setText(s);
为以下代码中的视图提供错误。 if(i == NUMBER_OF_QUERY - 1){ isThreadAlive = false; btnStart.setEnabled(true); btnSubmit.setEnabled(false); btnCancel.setEnabled(false); setButtonsDisabled(); }
我想知道,为什么会这样,怎么解决?
暂无答案!
目前还没有任何答案,快来回答吧!