我正在构建我的第一个应用程序和类似于 MasterMind 的简单游戏。我希望当电脑尝试找到我的号码时,不要立即显示他在找到正确号码之前所做的所有尝试,而是逐步显示。例如,CPU 说出第一个数字,等待一秒钟,然后说出第二个数字,依此类推。这是代码:
public void startCPU() {
int num;
int strike;
int xx;
do {
do {
Random random = new Random();
num = random.nextInt((9876 - 123) + 1) + 123;
xx = (int) numpos.pox[num];
} while (xx == 0);
Numeri.Confronta(mioNumero, numpos.pox[num]);
int ball = Risultati.getBall();
strike = Risultati.getStrike();
TextView txtv = (TextView) findViewById(R.id.numberthatcpusay);
if (numpos.pox[num] < 1000) {
Integer x = numpos.pox[num];
String s = ("0" + Integer.toString(x) + " " + Integer.toString(strike) + "X "
+ Integer.toString(ball) + "O" + " ");
txtv.append(s);
} else {
Integer x = numpos.pox[num];
String s = (Integer.toString(x) + " " + Integer.toString(strike) + "X "
+ Integer.toString(ball) + "O" + " ");
txtv.append(s);
}
numeroDato = numpos.pox[num];
numpos.pox[num] = 0;
for (int i = 0; i <= 9876; i++) {
if (Risultati.checkStrikeAndBall(numeroDato, numpos.pox[i], strike, ball) == true) {
numpos.pox[i] = 0;
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (strike != 4);
startMe();
}
问题是textView不会每秒更新,而是只有当CPU找到数字时才会更新。这样,当我单击启动此方法的按钮时,在看到结果之前我应该等待的时间与尝试次数相等。例如,如果 CPU 在找到正确的数字之前需要 9 个数字,我应该在 textView 显示所有尝试之前等待 9 秒。我该如何解决?
最佳答案
您不能在 UI 线程上执行此操作!
您正在运行一个在 UI 线程上调用 Thread.sleep()
的循环,这基本上会完全卡住手机。
考虑使用AsyncTask
.
在 doInBackground
方法中,您不在 UI 线程上,因此您可以调用 sleep。
每秒计算新的数字并调用publishProgress
来更新UI。
然后在 onProgressUpdate
回调中,您执行 TextView.append() 调用 - 因为它必须在 UI 线程上调用。
关于java - TextView 不同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33387328/