Simon 说按下按钮后按钮颜色不会 return 恢复正常

Simon Says button color won't return to normal after button press

public void flashButton(int color) {
    final ImageView colors = findViewById(R.id.buttonsImage);
    final int newColor = color;

    Handler handler = new Handler();
    final Runnable r = new Runnable() {
        public void run() {
            if(newColor == 1)
                colors.setImageResource(R.drawable.green_activated_png);
            if(newColor == 2)
                colors.setImageResource(R.drawable.yellow_activated_png);
            if(newColor == 3)
                colors.setImageResource(R.drawable.red_activated_png);
            if(newColor == 4)
                colors.setImageResource(R.drawable.blue_activated_png);

            System.out.println("Flashed color: " + newColor);
        }
    };
    handler.postDelayed(r, 1000);

    colors.setImageResource(R.drawable.normal_buttons);
    System.out.println("Returned Color.");
}

正在使用 R.drawable.green_activated_png) 更改每个按钮的按钮颜色。然后,我将其改回 (R.drawable.normal_buttons)。我认为我的问题出在 handler.postDelayed(r, 1000) 中。但是在用户按下正确的颜色后,颜色不会变回正常。

你这样做只是 opposite.You 必须在按下后立即更改 Button 的颜色,并且你必须将返回的颜色保持为 postDelayed 以便延迟给定时间后变为正常颜色。

public void flashButton(int color) {
    final ImageView colors = findViewById(R.id.buttonsImage);
    final int newColor = color;
    if(newColor == 1)
        colors.setImageResource(R.drawable.green_activated_png);
    if(newColor == 2)
        colors.setImageResource(R.drawable.yellow_activated_png);
    if(newColor == 3)
        colors.setImageResource(R.drawable.red_activated_png);
    if(newColor == 4)
        colors.setImageResource(R.drawable.blue_activated_png);
    System.out.println("Flashed color: " + newColor);

    Handler handler = new Handler();
    final Runnable r = new Runnable() {
        public void run() {
            colors.setImageResource(R.drawable.normal_buttons);
            System.out.println("Returned Color.");
        }
    };
    handler.postDelayed(r, 1000);
}

我认为函数的流程不正确。因为 post 延迟方法在 1 秒后执行。在此之前 colors.setImageResource(R.drawable.normal_buttons) 方法将被执行。改变流程如下

public void flashButton(int color) {
final ImageView colors = findViewById(R.id.buttonsImage);
final int newColor = color;
        if(newColor == 1)
            colors.setImageResource(R.drawable.green_activated_png);
        if(newColor == 2)
            colors.setImageResource(R.drawable.yellow_activated_png);
        if(newColor == 3)
            colors.setImageResource(R.drawable.red_activated_png);
        if(newColor == 4)
            colors.setImageResource(R.drawable.blue_activated_png);

Handler handler = new Handler();
final Runnable r = new Runnable() {
    public void run() {
        colors.setImageResource(R.drawable.normal_buttons);
    }
};
handler.postDelayed(r, 1000);
}