嗨,我是android delveloping的新手,我正在制作一个简单的游戏,在某种颜色变化时测试你的反射,测试我到目前为止学到的东西,但我无法解决出现的问题。 好吧,首先我将解释游戏是如何工作的: 当您点击屏幕时会出现随机延迟,之后您需要尽快再次点击屏幕以获得最佳分数,如果您在延迟结束之前点击,则游戏停止并告诉您再试一次。 我的问题是,当我第二次点击时,无论是在延迟之后还是更加错误,它都会重复一部分代码,我无法弄清楚原因。我发布了与下面相关的代码。如果你需要的话任何贬低让我知道!
P.S我觉得它与处理程序有关,但我不确定。 final Random random = new Random();
final int randomNumber = random.nextInt(10) + 1;
bestScoreView.setText("best score " + bestTime + " ms");
mainThing.setText("Tap to start");
mainThing.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
randomTimeDelay = randomNumber * 1000;
if (previousTapDetected){
mainThing.setText("You taped too fast");
mainThing.setBackgroundColor(ContextCompat
.getColor(getApplicationContext(), R.color.red));
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mainThing.setText("Try again");
}
}, 750);
}else if (previousTapDetected = true){
mainThing.setText("Wait for the color to change");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
previousTapDetected=false;
mainThing.setText("Tap now");
startTime = System.currentTimeMillis();
mainThing.setBackgroundColor(ContextCompat
.getColor(getApplicationContext(), R.color.red));
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mainThing.setText("You scored " + score + " ms");
mainThing.setEnabled(false);
}
}, 500);
}
}, randomTimeDelay);
endTime = System.currentTimeMillis();
score = endTime - startTime;
if (bestTime > score) {
bestScoreView.setText("Best score: " + score + " ms");
bestTime = score;
} else if (bestTime < score){
bestScoreView.setText("Best score " + bestTime + " ms");
}
}
}
});
答案 0 :(得分:0)
根据docs
当你创建一个新的Handler时,它被绑定到正在创建它的线程的线程/消息队列 - 从那时起,它将消息和runnables传递给该消息队列并在它们出现时执行它们消息队列
并且,在您的代码中,您正在尝试操作UI元素,因此应在 UI线程
上创建Handler
Handler handler = new Handler();
mainThing.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
randomTimeDelay = randomNumber * 1000;
if (previousTapDetected){
mainThing.setText("You taped too fast");
mainThing.setBackgroundColor(ContextCompat
.getColor(getApplicationContext(), R.color.red));
handler.postDelayed(new Runnable() {
@Override
public void run() {
mainThing.setText("Try again");
}
}, 750);